getopts
is a shell built-in.
0 $ eval set -- '-A -b'
0 $ getopts 'AaBb' opt
0 $ echo $opt
A
0 $ getopts 'AaBb' opt
0 $ echo $opt
b
0 $ getopts 'AaBb' opt
1 $ echo $opt
?
getopts1.sh
:
while getopts 'AaBb'; do
echo $opt
done
usage:
./getopts.sh -Ab
bug: 它会记录执行了多少次,也就是 parse 到第几个 argv,以此完成遍历。如果用于函数,则该函数只能调用一次。之后调用该函数 getopts
都是返回 ?
。
另外 coreutils 中有一个外部程序叫 getopt
,功能比这个强一些。