Shell 命令行解析 getopt工具

Linux下使用getopt工具进行命令行解析,可以同时处理长选项和短选项。

NAME
       getopt - parse command options (enhanced)

SYNOPSIS
       getopt optstring parameters
       getopt [options] [--] optstring parameters
       getopt [options] -o|--options optstring [options] [--] parameters

使用方法:

#!/bin/bash

# -o表示段选项,--long表示长选项
# 选项后面没有冒号表示没有参数,1个冒号表示必须有参数,2个冒号表示可选参数
# 对于具有可选参数的选项,没有没有提供值,会返回一个空字符串,并且会占用一个位置

TEMP=`getopt -o ab:c:: -l a-long,b-long:,c-long:: -n 'example.bash' -- "$@"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

eval set -- "$TEMP"

while true; do
    case "$1" in
        -a|--a-long)
            echo "Option a"
            shift
            ;;
        -b|--b-long)
            echo "Option b, argument \`$2'"
            shift 2
            ;;
        -c|--c-long)
            case "$2" in
                "")
                    echo "Option c, no argument"
                    shift 2
                    ;;
                *)
                    echo "Option c, argument \`$2'"
                    shift 2
                    ;;
            esac
            ;;
        --)
            shift
            break
            ;;
        *) 
            echo "Internal error!"
            exit 1
            ;;
    esac
done

echo "Remaining arguments:"
for arg do
   echo '--> '"\`$arg'" ;
done

双横岗的含义:

例如:set -- "$progname" "$@"

From help set:

  --  Assign any remaining arguments to the positional parameters.
      If there are no remaining arguments, the positional parameters
      are unset.

The reason for -- is to ensure that even if "$progname" or "$@" contain dashes, they will not be interpreted as command line options.

set changes the positional parameters, which is stored in $@. So in this case, it appends "$progname" to the beginning of the positional parameters received by the script.

posted @ 2020-07-02 21:34  IUNI_JM  阅读(377)  评论(0编辑  收藏  举报