Bash:使用 getopts 解析参数后的选项

Gau*_*tho 1 bash getopts

在请求一些参数(arg)和选项(-a)的脚本中,我想让脚本用户可以将选项放置在命令行中他想要的位置。

这是我的代码:

while getopts "a" opt; do
  echo "$opt"
done
shift $((OPTIND-1))

echo "all_end : $*"
Run Code Online (Sandbox Code Playgroud)

通过这个命令,我得到了预期的行为:

./test.sh -a arg
a
all_end : arg
Run Code Online (Sandbox Code Playgroud)

我想用这个命令得到相同的结果:

./test.sh arg -a
all_end : arg -a
Run Code Online (Sandbox Code Playgroud)

lar*_*sks 5

getopt命令(包的一部分util-linux,与 不同getopts)将执行您想要的操作。bash常见问题解答对使用它有一些意见,但老实说,现在大多数系统都会有现代版本的getopt.

考虑以下示例:

#!/bin/sh

options=$(getopt -o o: --long option: -- "$@")
eval set -- "$options"

while :; do
    case "$1" in
        -o|--option)
            shift
            OPTION=$1
            ;;
        --)
            shift
            break
            ;;
    esac

    shift
done

echo "got option: $OPTION"
echo "remaining args are: $@"
Run Code Online (Sandbox Code Playgroud)

我们可以这样称呼它:

$ ./options.sh -o foo arg1 arg2
got option: foo
remaining args are: arg1 arg2
Run Code Online (Sandbox Code Playgroud)

或者像这样:

$ ./options.sh  arg1 arg2 -o foo
got option: foo
remaining args are: arg1 arg2
Run Code Online (Sandbox Code Playgroud)