linux - 对于两个连续的选项, `getopts` 将第二个选项作为第一个选项的参数

标签 linux shell unix scripting

我有一个代码:

    while getopts ab:cde:f opt
    do
        case ${opt} in
            b|e)
                [[ ${OPTARG} = -* ]]   && usage "Invalid parameter \"${OPTARG}\" provided for agurment \"-        ${opt}!\""
                [[ ${#OPTARG} -eq 0 ]] && usage "Argument \"-${opt}\" requires a parameter!${OPTARG}"
            ;;
        esac

        case $opt in
            a) minusa=$opt;;
            b) minusb=$opt
            file_b=$OPTARG;;
            c) minusc=$opt;;
            d) minusd=$opt;;
            e) minuse=$opt
            file_e=$OPTARG;;
            f) minusf=$opt;;
            /?) echo Unrecognized parameter
             exit 1;;
        esac

    done
    echo  "minusa:$minusa","minusb:$minusb","file_b:$file_b","minusc:$minusc","minusd:$minusd","minuse:$minuse","file_e:$file_e","minusf:$minusf"

简单的代码,只是为了理解getopts命令的行为。当我像这样运行脚本时:

    ./eg2 -b -f
    ./eg2: line 7: usage: command not found
    minusa:,minusb:b,file_b:-f,minusc:,minusd:,minuse:,file_e:,minusf:

它将选项-b 的参数作为-f。而我想打印:

     [[ ${OPTARG} = -* ]]   && usage "Invalid parameter \"${OPTARG}\" provided for agurment \"-${opt}!\""

我在代码中到底哪里出错了?同样对于选项 -b-e 如果没有参数,我想打印:

    [[ ${#OPTARG} -eq 0 ]] && usage "Argument \"-${opt}\" requires a parameter!${OPTARG}"

请解释。

最佳答案

您在 getopts 行中的“b”之后放置了一个“:”。这告诉它期待之后的争论。如果您不希望下一个参数被视为 -b 的参数,请删除“:”。

关于linux - 对于两个连续的选项, `getopts` 将第二个选项作为第一个选项的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17326384/

相关文章:

linux - 在 Nsight Eclipse 中链接 libusb-1.0 库?

sql - 使用腻子将结果保存在平面文件中

unix - 获取文件大小并根据大小分割文件

linux - 你如何知道 Ubuntu 上安装了哪个版本的 GTK+?

linux - 如何挂载文件系统类型为 "devtmpfs"的硬盘

linux - 创建/删除许多硬链接(hard link)的缺点?

shell - 将脚本作为用户数据传递到 AWS EC2 spot 实例

shell - yum update 在脚本中调用时忽略排除

linux - 从所有 txt 文件中查找作为参数给出的字符串的 Grep 文件,并将它们复制到另一个目录

linux - 使用 ls 进行管道传输时,grep 命令在 solaris 中不起作用