前言
今天在改进自己的脚本,(此处省略300字)
教程
此次要用到的参数是getopts
。
getopts简介:
1.optstring定义脚本能够使用的参数
2.只支持短选项,不支持长选项。
3.如果想使用选项后面的参数,只需在选项后面加冒号(:)即可
4.默认情况下只能获取一个参数
用法为:
getopts optstring name [arg]
eg 1.
[root@localhost ~]# cat test.sh #!/bin/bash getopts a OPT echo $OPT [root@localhost ~]# ./test.sh -a a
eg 2.如果想使用选项后面的参数,只需在选项后面加冒号(:)即可
[root@localhost ~]# cat test.sh #!/bin/bash getopts a: OPT echo $OPT echo $OPTARG [root@localhost ~]# ./test.sh -a "this is a" a this is a
eg 3.如果不想让其输出错误信息,秩序在所有选项之前加上冒号(:)即可
[root@localhost ~]# cat a.sh #!/bin/bash getopts a: OPT echo $OPT echo $OPTARG [root@localhost ~]# ./a.sh -b ./a.sh: illegal option -- b ? [root@localhost ~]# cat a.sh #!/bin/bash getopts :a: OPT echo $OPT echo $OPTARG [root@localhost ~]# ./a.sh -b ? b
eg 4.如果想使用多个选项,需要使用循环语句
[root@localhost ~]# cat a.sh #!/bin/bash while getopts ":a:b:" OPT;do case $OPT in a) echo $OPT echo $OPTARG ;; b) echo $OPT echo $OPTARG ;; *) echo "wrong option" ;; esac done [root@localhost ~]# ./a.sh -a "this is a" a this is a [root@localhost ~]# ./a.sh -b "this is b" b this is b [root@localhost ~]# ./a.sh -c "this is c" wrong option
本文是博主为了方便使用,转自:liufeily 的BLOG:shell脚本之参数选项