您的位置:首页 > 运维架构 > Shell

getopt命令--用于shell脚本获取命令行选项

2018-02-05 17:51 441 查看
getopt命令

功能:主要用于shell脚本中,获取输入脚本的命令行参数

与此类似的还有getopts(bash内置的一个命令)

区别:getopt可以获取长选项参数,例如--example=123456789(长选项可以使用=号来附带参数值)这样的选项,同时,还可以获取-example,-test123456789(附带参数)这样的短选项,短选项不能使用=号来附带参数值。

getopts不能获取长选项。

getopt的经典使用是与set配合使用:set -- $(getopt xxxx),例如:set -- $(getopt -o ab:c:: --long along,blong:,clong:: -n 'example.sh' -- "$@")

set --命令将getopt获取的命令行结果赋予$1,$2...等内容。

通过这两个命令的相互组合,可以很轻松的处理shell脚本命令行选项。例如:

#!/bin/bash

#echo $@

#-o或--options选项后面接可接受的短选项,如ab:c::,表示可接受的短选项为-a -b -c,其中-a选项不接参数,-b选项后必须接参数,-c选项的参数为可选的
#-l或--long选项后面接可接受的长选项,用逗号分开,冒号的意义同短选项。
#-n选项后接选项解析错误时提示的脚本名字
ARGS=`getopt -o ab:c:: --long along,blong:,clong:: -n 'example.sh' -- "$@"`
if [ $? != 0 ]; then
echo "Terminating..."
exit 1
fi

#echo $ARGS
#将规范化后的命令行参数分配至位置参数($1,$2,...)
eval set -- "${ARGS}"

while true
do
case "$1" in
-a|--along)
echo "Option a";
shift
;;
-b|--blong)
echo "Option b, argument $2";
shift 2
;;
-c|--clong)
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

#处理剩余的参数
for arg in $@
do
echo "processing $arg"
done需要注意的是,像上面的-c选项,后面是可接可不接参数的,如果需要传递参数给-c选项,则必须使用如下的方式:
#./getopt.sh -b 123 -a -c456 file1 file2
Option b, argument 123
Option a
Option c, argument 456
processing file1
processing file2
#./getopt.sh --blong 123 -a --clong=456 file1 file2
Option b, argument 123
Option a
Option c, argument 456
processing file1
processing file2


代码部分转载自http://blog.csdn.net/sofia1217/article/details/52244582
          
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐