bash - 在 bash 中的自定义 getopts 脚本中将参数作为选项传递

标签 bash getopt getopts

我想将选项作为参数传递。例如:

mycommand -a 1 -t '-q -w 111'

脚本无法识别引号中的字符串。即它只获取字符串的一部分。

getopts 的工作原理相同 - 它只看到 -q

对于自定义 getopts,我使用类似的脚本(示例):

while :
do
    case $1 in
        -h | --help | -\?)
            # Show some help
            ;;
        -p | --project)
            PROJECT="$2"
            shift 2
            ;;
        -*)
            printf >&2 'WARN: Unknown option (ignored): %s\n' "$1"
            shift
            ;;
        *)  # no more options. Stop while loop
            break
            ;;
        --) # End of all options
        echo "End of all options"
            shift
            break
            ;;
    esac
done

最佳答案

也许我误解了这个问题,但 getopts 似乎对我有用:

while getopts a:t: arg
do
    case $arg in
        a)  echo "option a, argument <$OPTARG>"
            ;;
        t)  echo "option t, argument <$OPTARG>"
            ;;
    esac
done

运行:

bash gash.sh -a 1 -t '-q -w 111'
option a, argument <1>
option t, argument <-q -w 111>

这不是你想要的吗?也许您错过了带参数的选项后面的 :

关于bash - 在 bash 中的自定义 getopts 脚本中将参数作为选项传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30937996/

相关文章:

regex - sed - 只删除带元音的单词

c - 为什么gdb一直显示optarg为0x0

Perl GetOptions() 区分大小写

bash - 有人可以用简单的英语解释这个简短的 getopts bash 脚本吗? (UNIX)

linux - 如何在 getopts 上使用 ${OPTARG}?

bash - 在 bash 中使用 getopts 的 bool cli 标志?

Linux 脚本组添加

bash - 在非登录 shell 中执行的 shebang 中执行 bash 脚本的正确语法是什么

ruby - 我如何使用 Git 来识别存储库不同版本之间的功能更改?

c - 当有错误的命令行参数时,如何使 getopt_long() 不打印任何内容?