bash - 如何在 bash 中多次调用 getopts

标签 bash getopt

我有一个公共(public)库,我从几个解析命令行选项的脚本中使用它,但是我也希望我的各个脚本也能够处理参数... 例如

通用.sh:

function get_options {
    echo -e "in getoptions"
    echo $OPTIND
    while getopts ":ab:" optionName; do
       [ ... processing code ... ]
    done
}

a.sh

. ./common.sh

function get_local_options {
    echo -e "in getoptions"
    echo $OPTIND
    while getopts ":xy:" optionName; do
       [ ... processing code ... ]
    done
}

get_local_options $*
OPTIND=1
get_options $*

如果我调用 a.sh 的问题是:

a.sh -x -y foo -a -b bar

get_options 在“foo”处停止处理,因为它在第一个“非选项”处停止

在不自己重写东西的情况下有什么办法解决这个问题吗?

最佳答案

foo() {
  unset OPTIND
  while getopts ...
  do
  done
}

关于bash - 如何在 bash 中多次调用 getopts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2189281/

相关文章:

bash - fork /多线程进程 |狂欢

regex - 如何在 BASH 中查找和替换文件每一行的最后一个空格?

python - 输出文件在脚本完成之前不包含任何内容

c++ - 有没有办法将 "reset"getopt 用于非全局用途?

c - 为什么 `optarg` 没有被覆盖?

bash - 从文件名中查找 exec 和 strip 扩展名

linux - 从另一个 screen session 中启动 screen session

Shell 脚本 getopts optarg 无值

c - 为同一个选项获取多个值

从 getopt 转换参数