本文共 1527 字,大约阅读时间需要 5 分钟。
本文编辑自: 当我们我们向 脚本文件传递参数 可以通过 $1,$2 等特殊变量。很方便,但是有些限制,就是不能超过9个参数。通过使用 shift ,我们可以向脚本文件传递更多的参数,通过 getopts 我们能更方便地提取参数。 通过使用 shift ,我们将 shell脚本文件 的参数起点从左向右移。 在shift命令中可以给一个参数,以表示对shell脚本文件的传入参数启动从左向右移动多少。不给参数的话,表示移动一位。 注意:“
$#”表示shell脚本文件传入参数的个数。
如果你的脚本命令后有一些选项开关,比如 -i , -c 等等,这个时候使用shift来挨个查看比较麻烦。而用getopts则比较方便。getopts使用格式如下: getopts format_string variable h) echo "this is help information" v) echo "the version is 1.0.0" --)echo the option is end 这段脚本允许两个参数选项,分别是-h,-v,使用的时候可以分开来写,像-h -v,也可以连在一起,像-hv 运行命令“ sh test.sh -h -v Hello ”或 “ sh test.sh -hv Hello ” ,你将得到如下结果: 如果选项需要输入值,则在参数选项后面加上“ : ”,比如:getopts hvc: OPTION脚本在读到-c的时候,会把它的参数值存储在$OPTARG变量中。 while getopts hv:t: OPTION h) echo "this is option h" v) echo "this is option v.And the var is " $OPTARG t) echo "this is option t.And the var is " $OPTARG 运行命令“ sh test.sh -h -v vv -t tt hello ”将得到如下结果: this is option v.And the var is vv
this is option t.And the var is tt
转载地址:http://tgtmb.baihongyu.com/