执行linux的系统命令可以接不通的参数,比如 rm -rf test
,自己编写的脚本在被人调用时,怎么能提供更多参数选项实现更丰富的功能呢,怎么能让使用者-r -f
,甚至是-ip 192.168.0.1
呢?这些参数选项如何解析?
手工解析
主要用到了shift命令,shift的作用是将输入参数以空格为分割单位左移一个单位,即将最前边的第一个参数去掉,第二个变成第一个
#!/bin/bash
until [ -z "$1" ]
do
case $1 in
-path)
shift;path=$1;echo $path;shift
;;
-ip)
shift;ip=$1;echo $ip;shift
;;
-paasword)
shift;paasword=$1;echo $paasword;shift
;;
*)
echo "------"
exit 1
;;
esac
done
echo "end"
执行上述脚本,输入参数-path /opt -ip 192.168.0.1
,输入如下:
/opt
192.168.0.1
end
getopts和getopt
'getopts'是POSIX Shell中的内置命令,其使用方法是:
getopts <opt_string> <optvar> <arguments>
'getopt'相对于'getopts'更强大,能处理短选项和长选项,但是不是Shell内建的命令,而是'util-linux'这个软件包提供的功能,它不是POSIX标准的一部分,所以也有人建议不使用'getopt'
因为没有在项目中具体用过,就不细聊了,先占个坑,知道有这个玩意,想详细了解的,请参考这里
Refenence:
https://liam0205.me/2016/11/11/ways-to-parse-arguments-in-shell-script/
http://www.zmonster.me/2014/08/09/pare-arguments-in-shell-function.html