Linux shflags脚本

2022-8-31 17:56| 发布者: yangy| 查看: 873| 评论: 0

类目: A40i/T3系列产品  >  Linux     文档编号: 741

shflags有助于在脚本中简单地处理命令行的参数。

例:

#!/bin/sh
​
# source shflags
. /path/to/shflags   #引入脚本
​
# define a 'name' command-line string flag
# 设置string变量     选项名(--name) 默认值   参数介绍               缩写(-n)
DEFINE_string       'name'         'world' 'name to say hello to' 'n'
​
#自定义帮助信息
FLAGS_HELP="test
example:
1. ./hello_world.sh
2. ./hello_world.sh -n hello
3. ./hello_world.sh --name hello
"
​
# parse the command-line
#返回值:0(${FLAGS_TRUE})1(${FLAGS_FALSE}) 2 (${FLAGS_ERROR})
#将不识别的参数更新到$@
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
​
# say Hello!
echo "Hello, ${FLAGS_name}!"
echo $@

测试结果:

$ ./hello_world.sh
Hello, world!
​
$ ./hello_world.sh -n Kate
Hello, Kate!
​
$ ./hello_world.sh --name 'Kate Ward'
Hello, Kate Ward!
​
$ ./hello_world.sh --name 'Kate Ward' hello
Hello, Kate Ward!
hello
​
**自定义信息**
test
example:
1. ./hello_world.sh
2. ./hello_world.sh -n hello
3. ./hello_world.sh --name hello
​
flags:
-n,--name: name to say hello to (default: 'world')
-h,--[no]help: show this help (default: false)
​
**默认信息**
$ ./hello_world.sh -h
USAGE: ./hello_world.sh [flags] args
flags:
-h show this help
-n name to say hello to
  1. boolean 布尔 可使用${FLAGS_TRUE} 和${FLAGS_FALSE} 注意在shell中true是0 false是1

  2. float 浮点 在shell中是字符串,所以在比较的时候要按字符串的规则来 也就是使用 = 和 != 而不是使用 eq, ge, gt, le, lt, ne

  3. integer 整型 shell支持整型所以应该使用 (eq, ge, gt, …)

  4. string 字符串 那就是字符串


已解决

未解决

只是看看