检索第一个非选项命令行参数

use*_*147 6 bash shell wrapper

我正在尝试编写一个包装器shell脚本,每次调用命令时都会缓存信息.它只需要存储第一个非选项参数.例如,在

$ mycommand -o option1 -f another --spec more arg1 arg2
Run Code Online (Sandbox Code Playgroud)

我想要检索"arg1".

怎么能在bash中完成?

Dig*_*oss 9

使用getopt可能是要走的路.

如果你想在bash中看到参数扫描代码,那么非getopt方式​​是:

realargs="$@"
while [ $# -gt 0 ]; do
    case "$1" in
      -x | -y | -z)
        echo recognized one argument option $1 with arg $2
        shift
        ;;
      -a | -b | -c)
        echo recognized zero argument option $1, no extra shift
        ;;
      *)
        saveme=$1
        break 2
        ;;
    esac
    shift
done
set -- $realargs
echo saved word: $saveme
echo run real command: "$@"
Run Code Online (Sandbox Code Playgroud)