linux命令getopts

來源:互聯網
上載者:User

標籤:

一、getopts 簡介

  由於shell命令列的靈活性,自己編寫代碼判斷時,複雜度會比較高。使用內部命令 getopts 可以很方便地處理命令列參數。一般格式為:

getopts options variable

  getopts 的設計目標是在迴圈中運行,每次執行迴圈,getopts 就檢查下一個命令列參數,並判斷它是否合法。即檢查參數是否以 - 開頭,後面跟一個包含在 options 中的字母。如果是,就把匹配的選項字母存在指定的變數 variable 中,並返回退出狀態0;如果 - 後面的字母沒有包含在 options 中,就在 variable 中存入一個 ,並返回退出狀態0;如果命令列中已經沒有參數,或者下一個參數不以 - 開頭,就返回不為0的退出狀態。

 

二、使用舉例

cat args
#!/bin/bash
while getopts h:ms option
do
case "$option" in
h)
echo "option:h, value $OPTARG"
echo "next arg index:$OPTIND";;
m)
echo "option:m"
echo "next arg index:$OPTIND";;
s)
echo "option:s"
echo "next arg index:$OPTIND";;
\?)
echo "Usage: args [-h n] [-m] [-s]"
echo "-h means hours"
echo "-m means minutes"
echo "-s means seconds"
exit 1;;
esac
done

echo "*** do something now ***"
./args -h 100 -ms
option:h, value 100
next arg index:3
option:m
next arg index:3
option:s
next arg index:4
*** do something now ***
./args -t
./args: illegal option -- t
Usage: args [-h n] [-m] [-s]
-h means hours
-m means minutes
-s means seconds

註:

1.getopts 允許把選項堆疊在一起(如 -ms)

2.如要帶參數,須在對應選項後加 :(如h後需加參數 h:ms)。此時選項和參數之間至少有一個空白字元分隔,這樣的選項不能堆疊。

3.如果在需要參數的選項之後沒有找到參數,它就在給定的變數中存入 ? ,並向標準錯誤中寫入錯誤訊息。否則將實際參數寫入特殊變數 :OPTARG

4.另外一個特殊變數:OPTIND,反映下一個要處理的參數索引,初值是 1,每次執行 getopts 時都會更新。

linux命令getopts

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.