shell中可以在执行脚本或调用函数时传入参数(位置参数),记作$1,$2...。shell脚本可以像使用普通变量一样去饮用这些参数,唯一的区别只是位置参数是只读的。
虽然位置参数是只读的,但是可以使用shift命令来操作它们。shift命令具有如下效果:
1
=$
2
2 =$ 3
...
2 =$ 3
...
shift命令可以带参数的,如shift 2代表1=$3, ...
下面这段代码摘自“Learning The Bash Shell”,展示了如何使用while和shift来解析参数。
while [ -n
"
$(echo $1 | grep '-')
"
]
;
do
case $ 1 in
-a ) process option -a ;;
-b ) process option -b ;;
-c ) process option -c ;;
* ) echo 'usage: alice [-a] [-b] [-c] args ... '
exit 1
esac
shift
done
normal processing of arguments ...
case $ 1 in
-a ) process option -a ;;
-b ) process option -b ;;
-c ) process option -c ;;
* ) echo 'usage: alice [-a] [-b] [-c] args ... '
exit 1
esac
shift
done
normal processing of arguments ...
getopts命令是专用于参数解析的一个命令。如下:
while getopts
"
:ab:c
"
opt
;
do
case $ opt in
a ) process option -a ;;
b ) process option -b
$ OPTARG is the option's argument ;;
c ) process option -c ;;
? ) echo 'usage: alice [-a] [-b barg] [-c] args ... '
exit 1
esac
done
shift $(($ OPTIND - 1 ))
normal processing of arguments ...
case $ opt in
a ) process option -a ;;
b ) process option -b
$ OPTARG is the option's argument ;;
c ) process option -c ;;
? ) echo 'usage: alice [-a] [-b barg] [-c] args ... '
exit 1
esac
done
shift $(($ OPTIND - 1 ))
normal processing of arguments ...
getopts命令有两个参数。第一参数是一个包含“参数字符”和冒号的字符串。第二个参数指示了当前getopts命令解析出的“参数字符”(不带' - '字符,' ? '代表了未知参数字符)。另外,$OPTARG表示“参数字符”后所带的参数,$OPTIND表示总的参数个数。