getopts命令列引數處理

2021-07-05 06:24:39 字數 1676 閱讀 1433

一、getopts 簡介

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

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

二、使用舉例

cat args

#

!/bin/bash

while getopts h:ms option

docase "$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 時都會更新。

getopts命令列引數處理

一 getopts 簡介 由於shell命令列的靈活性,自己編寫 判斷時,複雜度會比較高。使用內部命令 getopts 可以很方便地處理命令列引數。一般格式為 getopts options variablegetopts 的設計目標是在迴圈中執行,每次執行迴圈,getopts 就檢查下乙個命令列引...

getopts命令列引數處理

一 getopts 簡介 由於shell命令列的靈活性,自己編寫 判斷時,複雜度會比較高。使用內部命令 getopts 可以很方便地處理命令列引數。一般格式為 getopts options variable getopts 的設計目標是在迴圈中執行,每次執行迴圈,getopts 就檢查下乙個命令列...

getopts命令列引數處理

一 getopts 簡介 由於shell命令列的靈活性,自己編寫 判斷時,複雜度會比較高。使用內部命令 getopts 可以很方便地處理命令列引數。一般格式為 getopts options variablegetopts 的設計目標是在迴圈中執行,每次執行迴圈,getopts 就檢查下乙個命令列引...