#!/bin/bash
# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh
# Example input and output (from the bash prompt):
# ./option_test.sh -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'
# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
#-o表示短選項(xiàng),兩個(gè)冒號(hào)表示該選項(xiàng)有一個(gè)可選參數(shù),可選參數(shù)必須緊貼選項(xiàng)
#如-carg 而不能是-c arg
#--long表示長(zhǎng)選項(xiàng)
#"$@"在上面解釋過(guò)
# -n:出錯(cuò)時(shí)的信息
# -- :舉一個(gè)例子比較好理解:
#我們要?jiǎng)?chuàng)建一個(gè)名字為 "-f"的目錄你會(huì)怎么辦?
# mkdir -f #不成功,因?yàn)?f會(huì)被mkdir當(dāng)作選項(xiàng)來(lái)解析,這時(shí)就可以使用
# mkdir -- -f 這樣-f就不會(huì)被作為選項(xiàng)。
TEMP=`getopt -o ab:c:: -l a-long,b-long:,c-long:: -n 'option_test.sh' -- "$@"`
echo "TEMP:{$TEMP}"
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
#set 會(huì)重新排列參數(shù)的順序,也就是改變$1,$2...$n的值,這些值在getopt中重新排列過(guò)了
eval set -- "$TEMP" #必須用eval
echo "\$#: $#"
for i in "$@"; do
echo "{$i}"
done
#經(jīng)過(guò)getopt的處理,下面處理具體選項(xiàng)。
while true ; do
case "$1" in
-a|--a-long) echo "Option a" ; shift ;;
-b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
-c|--c-long)
# c has an optional argument. As we are in quoted mode,
# an empty parameter will be generated if its optional
# argument is not found.
case "$2" in
"") echo "Option c, no argument"; shift 2 ;;
*) echo "Option c, argument \`$2'" ; shift 2 ;;
esac ;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
echo "Remaining arguments:"
for arg do
echo '--> '"\`$arg'" ;
done
==================================================================================
$ set -- a ' b '
$ echo $#
2
$ a="a ' b '"
$ set -- $a
$ echo $#
4
$ set -- "$a"
$ echo $#
1