【问题标题】:BASH - Options included in $@BASH - $@ 中包含的选项
【发布时间】:2018-12-05 07:59:34
【问题描述】:

我有一个处理文件的脚本,可以接受多个文件参数:

sh remove_engine file1 #single arg

sh remove_engine file1 file2 #multiple file arg

在脚本的顶部,我将这些与$@ 一起收集以循环遍历它们。

问题是我还要使用选项(以及getopts)...

sh remove_engine -ri file1 file2

...$@ 现在返回

-rvi file1 file2

脚本的其余部分将-ri 作为文件名。

也在脚本顶部附近,我有一个带有getopts的while循环

while getopts :rvi opt
do
    case"$opt" in
    v)      verbose="true";;
    i)      interactive="true";;
    r)      recursive="true";;
   [?])     echo "Usage..."
            exit;;
    esac
done

如何解析选项,然后从选项中分离出参数?

【问题讨论】:

    标签: bash unix arguments options


    【解决方案1】:

    来自man bash

    当遇到选项结束时,getopts 以 返回值大于零。 OPTIND设置为索引 第一个非选项参数,name 设置为 ?

    所以完整的代码是:

    #!/bin/bash
    
    while getopts :rvi opt; do
      case $opt in
        v) verbose=true ;;
        i) interactive=true ;;
        r) recursive=true ;;
        *) echo "Usage..."; exit 1 ;;
      esac
    done
    
    shift $((OPTIND-1))  # remove all the OPTIND-1 parsed arguments from "$@"
    
    echo "$@"  # use the remaining arguments
    

    【讨论】:

    • ... 请注意getopts 期望所有选项(及其参数,如果有)出现在任何非选项参数之前。它不会识别或返回出现在非选项参数之后的选项。
    • @JohnBollinger 是的。 “第一个非选项参数”是唯一的“分隔符”。
    • OPTIND 设置为第一个非选项参数的索引,因此shift $OPTIND 将从 arg 列表中删除选项 第一个非选项参数.您需要shift $(($OPTIND-1)),它将仅删除选项,并将所有非选项参数保留在列表中。
    • @GordonDavisson 谢谢,你是对的,我已经更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多