8. 用getopts處理命令行選項:
這裏的getopts命令和C語言中的getopt幾乎是一致的,因爲腳本的位置參量在有些時候是失效的,如ls -lrt等。這時候-ltr都會被保存在$1中,而我們實際需要的則是三個展開的選項,即-l、-r和-t。見如下帶有getopts的示例腳本:
/> cat > test3.sh
#!/bin/sh
while getopts xy options #x和y是合法的選項,並且將-x讀入到變量options中,讀入時會將x前面的橫線去掉。
do
case $options in
x) echo "you entered -x as an option" ;;
y) echo "you entered -y as an option" ;;
esac
done
/> ./test3.sh -xy
you entered -x as an option
you entered -y as an option
/> ./test3.sh -x
you entered -x as an option
/> ./test3.sh -b #如果輸入非法選項,getopts會把錯誤信息輸出到標準錯誤。
./test3.sh: illegal option -- b
/> ./test3.sh b #該命令不會有執行結果,因爲b的前面有沒橫線,因此是非法選項,將會導致getopts停止處理並退出。
/> cat > test4.sh
#!/bin/sh
while getopts xy options 2>/dev/null #如果再出現選項錯誤的情況,該重定向會將錯誤輸出到/dev/null。
do
case $options in
x) echo "you entered -x as an option" ;;
y) echo "you entered -y as an option" ;;
\?) echo "Only -x and -y are valid options" 1>&2 # ?表示所有錯誤的選項,即非-x和-y的選項。
esac
done
/> . ./test4.sh -g #遇到錯誤的選項將直接執行\?)內的代碼。
Only -x and -y are valid options
/> . ./test4.sh -xg
you entered -x as an option
Only -x and -y are valid options
/> cat > test5.sh
#!/bin/sh
while getopts xyz: arguments 2>/dev/null #z選項後面的冒號用於提示getopts,z選項後面必須有一個參數。
do
case $arguments in
x) echo "you entered -x as an option." ;;
y) echo "you entered -y as an option." ;;
z) echo "you entered -z as an option." #z的後面會緊跟一個參數,該參數保存在內置變量OPTARG中。
echo "\$OPTARG is $OPTARG.";
;;
\?) echo "Usage opts4 [-xy] [-z argument]"
exit 1 ;;
esac
done
echo "The number of arguments passed was $(( $OPTIND - 1 ))" #OPTIND保存一下將被處理的選項的位置,他是永遠比實際命令行參數多1的數。
/> ./test5.sh -xyz foo
you entered -x as an option.
you entered -y as an option.
you entered -z as an option.
$OPTARG is foo.
The number of arguments passed was 2
/> ./test5.sh -x -y -z boo
you entered -x as an option.
you entered -y as an option.
you entered -z as an option.
$OPTARG is boo.
The number of arguments passed was 4
9. eval命令與命令行解析:
eval命令可以對命令行求值,做Shell替換,並執行命令行,通常在普通命令行解析不能滿足要求時使用。
/> set a b c d
/> echo The last argument is \$$#
The last argument is $4
/> eval echo The last argument is \$$# #eval命令先進行了變量替換,之後再執行echo命令。
The last argument is d