Shell传入参数的处理
2017-04-03 09:27
369 查看
引言
写程序的时候经常要处理命令行参数,本文描述在Bash下的命令行处理方式。选项与参数:
如下一个命令行:
./test.sh -f config.conf -v --prefix=/home
我们称-f为选项,它需要一个参数,即config.conf, -v 也是一个选项,但它不需要参数。
--prefix我们称之为一个长选项,即选项本身多于一个字符,它也需要一个参数,用等号连接,当然等号不是必须的,/home可以直接写在--prefix后面,即--prefix/home,更多的限制后面具体会讲到。
1. $# 传递到脚本的参数个数。
2. $* 以一个单字符串显示所有向脚本传递的参数。与位置变量不同,此选项参数可超过9个
3. $$ 脚本运行的当前进程ID号
4. $! 后台运行的最后一个进程的进程ID号
5. $@ 与$#相同,但是使用时加引号,并在引号中返回每个参数
6. $- 显示shell使用的当前选项,与set命令功能相同
7. $? 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。
变量 含义
8.$0 脚本名字 $1 位置参数 #1 $2 - $9 位置参数 #2 - #9 ${10} 位置参数 #10
9.$# 位置参数的个数 "$*" 所有的位置参数(作为单个字符串) * "$@" 所有的位置参数(每个都作为独立的字符串)
10.${#*} 传递到脚本中的命令行参数的个数
11.${#@} 传递到脚本中的命令行参数的个数
12.$_ 之前命令的最后一个参数
使用shell处理的时候对参数的处理是个基本模块,所以今天找到一篇简单易懂的文章来进行参考,作为以后shell参数处理的模板,推荐使用getopts形式进行参数的处理。如果需要支持长选项可以使用getopt
在bash中,可以用以下三种方式来处理命令行参数,每种方式都有自己的应用场景。
1、 手工处理方式
2、 getopts
3、 getopt
下面我们依次讨论这三种处理方式。
1. 手工处理方式
在手工处理方式中,首先要知道几个变量,还是以上面的命令行为例:$0 : ./test.sh,即命令本身,相当于C/C++中的argv[0]
$1 : -f,第一个参数.
$2 : config.conf
$3, $4 ... :类推。
$# 参数的个数,不包括命令本身,上例中$#为4.
$@ :参数本身的列表,也不包括命令本身,如上例为 -f config.conf -v --prefix=/home
$* :和$@相同,但"$*" 和 "$@"(加引号)并不同,"$*"将所有的参数解释成一个字符串,而"$@"是一个参数数组。如下例所示:
#!/bin/bash
for arg in "$*"
do
echo $arg
done
for arg in "$@"
do
echo $arg
done
执行./test.sh -f config.conf -n 10 会打印:
-f config.conf -n 10 #这是"$*"的输出
#以下为$@的输出
-f
config.conf
-n
10
所以,手工处理的方式即对这些变量的处理。因为手工处理高度依赖于你在命令行上所传参数的位置,所以一般都只用来处理较简单的参数。如
./test.sh 10
而很少使用./test -n 10这种带选项的方式。 典型用法为:
#!/bin/bash
if [ x$1 != x ]
then
#...有参数
else
then
#...没有参数
fi为什么要使用 x$1 != x 这种方式来比较呢?想像一下这种方式比较:
if [ -n $1 ] #$1不为空
但如果用户不传参数的时候,$1为空,这时 就会变成 [ -n ] ,所以需要加一个辅助字符串来进行比较。
手工处理方式能满足大多数的简单需求,配合shift使用也能构造出强大的功能,但在要处理复杂选项的时候建议用下面的两种方法。
2. getopts
处理命令行参数是一个相似而又复杂的事情,为此,C提供了getopt/getopt_long等函数,C++的boost提供了Options库,在shell中,处理此事的是getopts和getopt.
getopts和getopt功能相似但又不完全相同,其中getopt是独立的可执行文件,而getopts是由Bash内置的。
先来看看参数传递的典型用法:
./test.sh -a -b -c : 短选项,各选项不需参数
./test.sh -abc : 短选项,和上一种方法的效果一样,只是将所有的选项写在一起。
./test.sh -a args -b -c :短选项,其中-a需要参数,而-b -c不需参数。
./test.sh --a-long=args --b-long :长选项
我们先来看getopts,它不支持长选项。
使用getopts非常简单:
代码
#test.sh
#!/bin/bash
while getopts "a:bc" arg #选项后面的冒号表示该选项需要参数
do
case $arg in
a)
echo "a's arg:$OPTARG" #参数存在$OPTARG中
;;
b)
echo "b"
;;
c)
echo "c"
;;
?) #当有不认识的选项的时候arg为?
echo "unkonw argument"
exit 1
;;
esac
done现在就可以使用:
./test.sh -a arg -b -c
或
./test.sh -a arg -bc
来加载了。
getopts的使用形式是:getopts option_string variable
getopts一共有两个参数,第一个是-a这样的选项,第二个参数是 hello这样的参数。
选项之间可以通过冒号:进行分隔,也可以直接相连接,:表示选项后面必须带有参数,如果没有可以不加实际值进行传递
例如:getopts ahfvc: option表明选项a、h、f、v可以不加实际值进行传递,而选项c必须取值。使用选项取值时,必须使用变量OPTARG保存该值。
[hello@Git shell]$ bash test.sh -a hello -b this is -a the arg is ! hello test.sh: option requires an argument -- b Invalid option: - [hello@Git shell]$ bash test.sh -a hello -b hello -c this is -a the arg is ! hello this is -b the arg is ! hello this is -c the arg is ! [hello@Git shell]$ more test.sh #!/bin/bash while getopts "a:b:cdef" opt; do case $opt in a) echo "this is -a the arg is ! $OPTARG" ;; b) echo "this is -b the arg is ! $OPTARG" ;; c) echo "this is -c the arg is ! $OPTARG" ;; \?) echo "Invalid option: -$OPTARG" ;; esac done [hello@Git shell]$执行结果结合代码显而易见。同样你也会看到有些代码在a的前面也会有冒号,比如下面的
情况一,没有冒号:
[hello@Git shell]$ bash test.sh -a hello this is -a the arg is ! hello [hello@Git shell]$ bash test.sh -a test.sh: option requires an argument -- a Invalid option: - [hello@Git shell]$ more test.sh #!/bin/bash while getopts "a:" opt; do case $opt in a) echo "this is -a the arg is ! $OPTARG" ;; \?) echo "Invalid option: -$OPTARG" ;; esac done [hello@Git shell]$情况二,有冒号:
[hello@Git shell]$ bash test.sh -a hello this is -a the arg is ! hello [hello@Git shell]$ bash test.sh -a [hello@Git shell]$ more test.sh #!/bin/bash while getopts ":a:" opt; do case $opt in a) echo "this is -a the arg is ! $OPTARG" ;; \?) echo "Invalid option: -$OPTARG" ;; esac done情况一输入 -a 但是后面没有参数的的时候,会报错误,但是如果像情况二那样就不会报错误了,会被忽略。
getopts option_string variable
其中option_string中包含一个有效的单字符选项。若getopts命令在命令行中发现了连字符,那么它将用连字符后面的字符同 option_string相比较。若有匹配,则把变量variable的值设为该选项。若无匹配,则variable设为?。当getopts发现连字符后面没有字符,会返回一个非零的状态值。Shell程序中可以利用getopts的返回值建立一个循环。
有时侯选项中还带一个值,getopts命令同样也支持这一功能。这时需要在option_string中选项字母后加一个冒号。当 getopts命令发现冒号后,会从命令行该选项后读取该值。若该值存在,那么将被存在一个特殊的变量OPTARG中。如果该值不存在,getopts命令将在OPTARG中存放一个问号,并且在标准错误输出上显示一条消息。
optstring option字符串,会逐个匹配
varname 每次匹配成功的选项
arg 参数列表,没写时它会取命令行参数列表
$OPTIND 特殊变量,option index,会逐个递增, 初始值为1
$OPTARG 特殊变量,option argument,不同情况下有不同的值
细则1:
当optstring以”:“开头时,getopts会区分invalid option错误和miss option argument。 invalid option错误时,varname会被设成?,$OPTARG是出问题的option;miss option argument时,varname会被设成:(在我的fedora系统里测试OPTARG为?),$OPTARG是出问题的option.
当optstring不以”:“开头,invalid option错误和miss option argument错误都会使varname被设成?, $OPTARG是出问题的option(在我的fedora系统里测试OPTARG为空).
细则2:
当optstring中的字母跟”:“时,表明该option可接参数,参数(argument)放在$OPTARG中,如果缺参数,且optstring是以”:“开头,则varname的值会是:(在我的fedora系统里测试OPTARG为?),$OPTARG是该option, 否则varname的值是?,$OPTARG是该option.(参照细则1)(在我的fedora系统里测试OPTARG为空)
#!/bin/bash if [[ $# -lt 1 ]];then echo "USAGE:`basename $0` [-a] [-b value] [-c]" exit 1 fi while getopts :ab:c name do case $name in a) aflag=1 echo "a" ;; b) bflag=1 if [[ ${OPTARG:0:1} = "-" ]]; then echo "invalid parameter of $OPTARG" exit 1 fi bval=$OPTARG ;; c) cflag=1 echo "c" ;; \?) echo "Invalid option :`basename $0` [-a] [-b value] [-c]" exit 1 ;; :) echo "$0:Must supply an argument to -$OPTARG." exit 1 ;; esac done echo $bval在getopts分析选项时,如果-b后面不带参数,直接跟-c的话,那么-c将作为-b的参数。
下面是一个简单例子(脚本为getopt):
#/bin/bash echo $0 echo $* while getopts ":a:bc" opt do case $opt in a ) echo $OPTARG echo $OPTIND;; b ) echo "b $OPTIND";; c ) echo "c $OPTIND";; ? ) echo "error" exit 1;; esac done echo $OPTIND echo $* shift $(($OPTIND - 1)) echo $* echo $0 运行sh getopt.sh -a 12 -b -c 34 -m 输出: getopt.sh -a 12 -b -c 34 12 3 b 4 c 5 5 -a 12 -b -c 34 34 getopt.sh可以得出一些结论:
1、$0在用sh 或者 ./执行脚本时,指的是脚本名,用source或.执行时,永运是bash,这也反应了sh 或者 ./执行脚本的原理和source的方式是不同的.
2、$1 (1....n)指的第一个参数到....第n个参数
3、OPTARG存储相应选项的参数 OPTIND指向的是下一个参数的index
4、shift 会改变参数的顺序,通过左移去掉某些参数
5、getopts检测到非法参数就会停止,比如上例中遇到34就会终止,并不会去检测-m了,也就是说只要前一个参数是合法的(包含在option_string中的),就会继续检测下一个参数。
另外: unset OPTIND 可以解决shell脚本的函数中使用getopts
3. getopt
应该说绝大多数脚本使用该函数就可以了,如果需要支持长选项以及可选参数,那么就需要使用getopt.下面是getopt自带的一个例子:
#!/bin/bash # A small example program for using the new getopt(1) program. # This program will only work with bash(1) # An similar program using the tcsh(1) script language can be found # as parse.tcsh # Example input and output (from the bash prompt): # ./parse.bash -a par1 'another arg' --c-long 'wow!*/?' -cmore -b " very long " # Option a # Option c, no argument # Option c, argument `more' # Option b, argument ` very long ' # Remaining arguments: # --> `par1' # --> `another arg' # --> `wow!*/?' # Note that we use `"$@"' to let each command-line parameter expand to a # separate word. The quotes around `$@' are essential! # We need TEMP as the `eval set --' would nuke the return value of getopt. #-o表示短选项,两个冒号表示该选项有一个可选参数,可选参数必须紧贴选项 #如-carg 而不能是-c arg #--long表示长选项 #"$@"在上面解释过 # -n:出错时的信息 # -- :举一个例子比较好理解: #我们要创建一个名字为 "-f"的目录你会怎么办? # mkdir -f #不成功,因为-f会被mkdir当作选项来解析,这时就可以使用 # mkdir -- -f 这样-f就不会被作为选项。 TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: / -n 'example.bash' -- "$@"` if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi # Note the quotes around `$TEMP': they are essential! #set 会重新排列参数的顺序,也就是改变$1,$2...$n的值,这些值在getopt中重新排列过了 eval set -- "$TEMP" #经过getopt的处理,下面处理具体选项。 while true ; do case "$1" in -a|--a-long) echo "Option a" ; shift ;; -b|--b-long) echo "Option b, argument /`$2'" ; shift 2 ;; -c|--c-long) # c has an optional argument. As we are in quoted mode, # an empty parameter will be generated if its optional # argument is not found. case "$2" in "") echo "Option c, no argument"; shift 2 ;; *) echo "Option c, argument /`$2'" ; shift 2 ;; esac ;; --) shift ; break ;; *) echo "Internal error!" ; exit 1 ;; esac done echo "Remaining arguments:" for arg do echo '--> '"/`$arg'" ; done比如我们使用
./test -a -b arg arg1 -c
你可以看到,命令行中多了个arg1参数,在经过getopt和set之后,命令行会变为:
-a -b arg -c -- arg1
$1指向-a,$2指向-b,$3指向arg,$4指向-c,$5指向--,而多出的arg1则被放到了最后。
shell getopt 获取参数
#!/bin/sh #说明 show_usage="args: [-i , -p , -u , -w , -a , -s , -d , -v ]\ [--ip=, --port=, --user=, --pwd=, --path=, --script=, --debug=, --version=]" #参数 opt_ip="" opt_port="" opt_user="" opt_pwd="" opt_path="" opt_script="" opt_debug="" opt_version="" GETOPT_ARGS=`getopt -o i:p:u:w:a:s:d:v: -al ip:,port:,user:,pwd:,path:,script:,debug:,version: -- "$@"` eval set -- "$GETOPT_ARGS" #获取参数 while [ -n "$1" ] do case "$1" in -i|--ip) opt_ip=$2; shift 2;; -p|--port) opt_port=$2; shift 2;; -u|--user) opt_user=$2; shift 2;; -w|--pwd) opt_pwd=$2; shift 2;; -a|--path) opt_path=$2; shift 2;; -s|--script) opt_script=$2; shift 2;; -d|--debug) opt_debug=$2; shift 2;; -v|--version) opt_version=$2; shift 2;; --) break ;; *) echo $1,$2,$show_usage; break ;; esac done if [[ -z $opt_ip || -z $opt_port || -z $opt_user || -z $opt_pwd || -z $opt_path || -z $opt_script || -z $opt_debug || -z $opt_version ]]; then echo $show_usage echo "opt_ip:"$opt_ip",opt_port:"$opt_port",opt_user:"$opt_user",opt_pwd:"$opt_pwd",opt_path:"$opt_path",opt_script:"$opt_script",opt_debug:"$opt_debug",opt_version:"$opt_version exit 0 fi #开始处理 #ip port user pwd 连接服务器 #script path debug version 作为参数执行有几个关键会被忽略导致失败的地方:
eval set -- "$GETOPT_ARGS" eval关键字是必须的,网上好多例子没有,坑爹
GETOPT_ARGS=`getopt -o i:p:u:w:a:s:d:v: -al ip:,port:,user:,pwd:,path:,script:,debug:,version: -- "$@"`
最后的--也是必须的,网上好多例子也没有,坑爹
shift其实很简单的,就是左移参数列表,shift一次就将最左边的参数$1移出去了,然后
原来的$2现在就变成了$1。
shift后面还可以带上一个数字,指明要移出多少个参数(默认只移出一个),比如说
shift 3 就是移出3个参数,之后原来的$4就变成了现在的$1。
eval就是先将后面的参数执行一遍,将必要的置换都做了,再来执行命令。
总结
一般小脚本手工处理也许就够了,getopts能处理绝大多数的情况,getopt较复杂,功能也更强大。相关文章推荐
- shell--传入参数的处理
- shell传入参数的处理
- shell--传入参数的处理
- Shell传入参数的处理
- Shell传入参数的处理
- 参数处理-Shell传入参数的处理
- 参数处理-Shell传入参数的处理
- shell--传入参数的处理
- shell--传入参数的处理
- shell--传入参数的处理
- shell命令行选项与修传入参数处理
- shell传入参数处理方式
- shell--传入参数的处理
- shell--传入参数的处理
- 使用getopt处理shell脚本的参数 推荐
- VC启动另一个exe 同时传入参数 systerm WinExec ShellExecuteEx
- [Linux] 删除Shell传入的参数多余的后缀(如filename.apk.bak --> filename.apk)
- Bash Shell中命令行选项/参数处理
- shell关于参数的处理(转)
- 使用getopts处理Shell脚本参数