在bash脚本中使用getopts的最简单、最直接的方法是什么。
如果我有一个名为:myscript的脚本,它可以接受参数:-p -r -s -x
if argument x then exit
if argument p then echo "port 10"
if argument s then add 2+2
if argument r then echo env
这是一个假设的脚本,但我只想看一个如何完成的示例。
while getopts :xpsr opt; do
case $opt in
x ) exit ;;
p ) echo port 10 ;;
s ) (( 2 + 2 )) ;;
r ) echo env ;;
\? ) echo "${0##*/}" [ -xpsr ]; exit 1 ;;
esac
done
usage()
{
echo "Usage: $0 [-o <offset>] [-h];"
exit 0;
}
# -o (offset) need a value
# -h prints help
offset=0 # 0 is default offset
while getopts o:s opt
do
case "$opt" in
d) offset="$OPTARG";; # changing offset
s) usage # calls function "usage"
\?) echo "$OPTARG is an unknown option"
exit 1;; # all other options
esac
done
shift $((OPTIND-1))