執(zhí)行l(wèi)inux的系統命令可以接不通的參數,比如 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"
執(zhí)行上述腳本,輸入參數-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