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

Kir*_*rby 2 bash getopt getopts

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

mycommand -a 1 -t '-q -w 111'
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

cda*_*rke 5

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

while getopts a:t: arg
do
    case $arg in
        a)  echo "option a, argument <$OPTARG>"
            ;;
        t)  echo "option t, argument <$OPTARG>"
            ;;
    esac
done
Run Code Online (Sandbox Code Playgroud)

跑步:

bash gash.sh -a 1 -t '-q -w 111'
option a, argument <1>
option t, argument <-q -w 111>
Run Code Online (Sandbox Code Playgroud)

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