blog:shell:07_shell_command_getopt

Shell getopt命令

getopt用于在shell中解析命令行参数

语法: getopt [options] [--] optstring parameters getopt [options] -o|--options optstring [options] [--] parameters

optstring 从第一个非options的参数开始,或者在-- 第一次出现的位置后面 -o或者--options表示后面的为short option的optstring 如果-o--options指定,那么这个optstring被认为是short options string

short optstring的格式如下: 例如: ab:c:: 表示可以接收的short option为-a -b -c 其中-a不需要参数, -b选项必须要有参数, -c选项的参数是可选的

-l 或者 --longoptions表示后面的optstring为long option string 如果有多个长选项,则用逗号分隔 例如: along,blong:clong:: 和short optstring类似, --along不需要参数, --blong需要要有参数 --clong是可选参数.

使用示例:

ARGS=getopt -o ab:c:: --long along,blong:,clong:: -n 'example.sh' -- "$@"
if [ $? != 0 ]; then
    echo "Terminating..."
    exit 1
fi

echo "ARGS is:$ARGS"
#将规范化后的命令行参数分配至位置参数($1,$2,...)
#如果arguments以'+'或者'-'开头,则需要在set命令后紧跟'--',用来分割参数
eval set -- "${ARGS}"
echo "after eval, ARGS is:$ARGS"

while true
do
    case "$1" in
        -a|--along) 
            echo "Option a";
            ;;
        -b|--blong)
            echo "Option b, argument $2";
            shift
            ;;
        -c|--clong)
            case "$2" in
                "")
                    echo "Option c, no argument";
                    ;;
                *)
                    echo "Option c, argument $2";
                    ;;
            esac
            shift
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Internal error!"
            exit 1
            ;;
    esac

    shift
done


#处理剩余的参数
for arg in $@
do
    echo "processing $arg"
done
使用示例:
$ ./getopt.sh -a --along -b tux --blong tux -ca --clong=a readme.txt

ARGS is: -a --along -b 'tux' --blong 'tux' -c 'a' --clong 'a' -- 'readme.txt'
after eval, ARGS is: -a --along -b 'tux' --blong 'tux' -c 'a' --clong 'a' -- 'readme.txt'
Option a
Option a
Option b, argument tux
Option b, argument tux
Option c, argument a
Option c, argument a
processing readme.txt

注意:

  对于可选参数c后面的参数一定要紧跟c, 对于可选长参数需要使用等号
  • blog/shell/07_shell_command_getopt.txt
  • 最后更改: 2022/01/09 17:32
  • 127.0.0.1