Shell script中使用getopt例子 使用getopt可以非常方便的格式話選項跟對應的參數,例子如下 www.2cto.com Shell代碼 #!/bin/bash set -- `getopt -q ab:c "$@"` while [ -n "$1" ] do case "$1" in -a) echo "option -a";; -b) value="$2" echo "option -b with para $value" shift;; -c) echo "option -c";; --) shift break;; *) echo "$1 not option";; esac shift done count=1 for para in "$@" do echo "#$count=$para" count=$[$count+1] done ./test -ab test1 -cd test2 test3 test4 結果:option -a option -b with para 'test1' option -c #1='test2' #2='test3' #3='test4' getopt 用法: getopt options optstring parameters 對於./test -ab test1 -cd "test2 test3" test4 這樣的參數類型,getopt是無能為力的。這就需要getopts了 www.2cto.com Shell代碼 #!/bin/bash while getopts :ab:c opt do case $opt in a) echo "-a option";; b) echo "-b option with value $OPTARG";; c) echo "-c option";; *) echo $opt not a option;; esac done OPTARG 環境變數存放對應選項的參數 ./test -ab "hello,world" -cdefg 結果: -a option -b option with value hello,world -c option ? not a option ? not a option ? not a option ? not a option 命令參數的處理 Shell代碼 #!/bin/bash while getopts :ab:cd opt do case $opt in a) echo "-a option";; b) echo "-b option with value $OPTARG";; c) echo "-c option";; d) echo "-d option";; *) echo $opt not a option;; esac done count=1 shift $[$OPTIND-1] for para in "$@" do echo "#$count=$para" count=$[$count+1] done ./test -abtest1 -cd test2 test3 test4 結果: www.2cto.com -a option -b option with value test1 -c option -d option #1=test2 #2=test3 #3=test4 OPTIND環境變數存放getopts命令剩餘的參數列表當前位值 用法:getopts optstring variable