代碼示例
#!/bin/bash
# getopts 獲取參數(shù)
# 一次只處理命令行上檢測(cè)到的一個(gè)參數(shù),處理完所有參數(shù)后會(huì)返回一個(gè)大于0的狀態(tài)碼,非常適合在循環(huán)中解析命令行所有參數(shù)
# 格式:getopts optstring variable
# optstring : 參數(shù)列表,如果選項(xiàng)需要跟一個(gè)選項(xiàng)值,則需要在選項(xiàng)后加一個(gè)冒號(hào),如果沒(méi)有選項(xiàng)值,則可以直接寫選項(xiàng)名稱,如果想要系統(tǒng)不提示錯(cuò)誤信息,可以所有的選項(xiàng)前也就是optstring前加一個(gè)冒號(hào)
# variable : 會(huì)將當(dāng)前參數(shù)保存在命令行中定義的variable變量中
# 字符“*”表示剩余的所有參數(shù)選項(xiàng)
while getopts :a:b:c opt
do
case "$opt" in
a) echo "found the a option, with the value is ${OPTARG}";;
b) echo "found the b option, with the value is ${OPTARG}";;
c) echo "found the c option";;
*) echo "Unknown option $OPTARG";;
esac
done
執(zhí)行結(jié)果
[root@localhost shell_script]# ./16.sh -d -a hello -b world
Unknown option d
found the a option, with the value is hello
found the b option, with the value is world
[root@localhost shell_script]# ./16.sh -d -a hello -b world -d -r -g
Unknown option d
found the a option, with the value is hello
found the b option, with the value is world
Unknown option d
Unknown option r
Unknown option g
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。