处理命令行参数是一个相似而又复杂的事情,为此,C提供了getopt/getopt_long等函数,
C++的boost提供了Options库,在shell中,处理此事的是getopts和getopt. getopts和getopt功能相似但又不完全相同,其中getopt是独立的可执行文件,而getopts是由Bash内置的。
先来看看参数传递的典型用法:
./test.sh -a -b -c: 短选项,各选项不需参数./test.sh -abc: 短选项,和上一种方法的效果一样,只是将所有的选项写在一起。./test.sh -a args -b -c:短选项,其中-a需要参数,而-b -c不需参数。./test.sh --a-long=args --b-long:长选项
使用getopts非常简单:
#test.sh
#!/bin/bash
while getopts "a:bc" arg #选项后面的冒号表示该选项需要参数
do
case $arg in
a)
echo "a's arg:$OPTARG" #参数存在$OPTARG中
argument1=$OPTARG
;;
b)
echo "b"
branch=1
;;
c)
echo "c"
iscar=1
;;
?) #当有不认识的选项的时候arg为?
echo "unkonw argument"
exit 1
;;
esac
done现在就可以使用:
./test.sh -a arg -b -c或
./test.sh -a arg -bc来加载了。
应该说绝大多数脚本使用该函数就可以了,如果需要支持长选项以及可选参数,那么就需要使用getopt.
References
- [linux-shell脚本中的参数解析](https://www.cnblogs.com/Vincent-yuan/p/16223057.htm