This topic created in 4616 days ago, the information mentioned may be changed or developed.
如何判断shell的函数参数是带0个1个或两个'-'符号,比如:
function test() {
if [ $1 == "" ]; then
do something;
fi
}
如果要让函数接受 x -x --x 这三种形式都可以工作,这个参数判断应该怎么写啊?求指教
7 replies • 1970-01-01 08:00:00 +08:00
 |
|
1
gastlygem Oct 16, 2013
如果需求很简单的话用这个应该就行: if [ $1 == "x" ] || [ $1 == "-x" ] || [ $1 == "--x" ]
正经的复杂参数处理应该使用getopts,详细用法需要查查文档。
个人觉得用得最爽的还是Python加命令行处理库argparse或者别的啥。
|
 |
|
2
lululau Oct 16, 2013
getopts 功能太简单,不支持长选项, getopt 命令可移植性又不好,所以我觉得像包含了长选项等等比较复杂的命令行选项处理的话,直接交给 ruby/python 等脚本语言来处理吧,别用 shell 写了
|
 |
|
4
hitsmaxft Oct 16, 2013
如果是要涉及到统计 -xx 的个数,顺手写了个工具函数
function test () { count=0 ; for arg in "${@[@]}" ; do [[ "$arg" != "${arg#-}" ]] && count=$(( $count +1)) done echo $count }
|
 |
|
5
yboren Oct 16, 2013
getopt或者getopt_long
|