#!/bin/sh
AFLAG=false
BFLAG=false
CFLAG=false
VALUE=
OPT=
while getopts abc: OPT
do
case $OPT in
a) AFLAG=TRUE ;;
b) BFLAG=TRUE ;;
c) CFLAG=TRUE
VALUE=$OPTARG ;;
\?) echo "Usage: $0 [-ab] [-c value] parameter" 1>&2
exit 1 ;;
esac
done
shift `expr $OPTIND - 1`
if [ "$AFLAG" = "TRUE" ]; then
echo "option a is specified."
fi
if [ "$BFLAG" = "TRUE" ]; then
echo "option b is specified."
fi
if [ "$CFLAG" = "TRUE" ]; then
echo "option c is specified, and VALUE is $VALUE"
fi
echo "parameter is $1"
このコマンドで利用できるオプションはa
、b
、c
です。
c
オプションは値を指定するオプションでwhile getoputs c:
というように:
をつけます。
OPTはgetopts
コマンドが使用する変数です。
OPTにはコマンド行のオプションの値(ここではa
, b
,c
)を順番に代入していきます。
-c
がコマンド行に場合は、$OPTARG
という変数にオプションに指定された値を代入します。
$OPTIND
はオプション処理に関わった部分の次の文字列の位置を示します。
command -c xyz -b wwwww
option b is specified.
option c is specified, and VALUE is xyz
であれば、$OPTARG
は4となり、shift 3
が実行されることになり、$1がwwwww
となります。
#!/bin/sh
if [ "$1" = "-v" ]; then
VERBOSE=TRUE
shift
fi
for param in "$@"
do
echo $param
done
オプションが1つの場合は、getopts
コマンドを使わずに上記のようにも書けます。