【问题标题】:Take many of the same type of cli argument in a shell script?在 shell 脚本中使用许多相同类型的 cli 参数?
【发布时间】:2017-09-11 22:46:50
【问题描述】:

在 shell 脚本中,可能是 bash,我们如何获取许多相同类型的参数并将它们添加到内部数组中?一个例子是这样的:

./combine -f file1 -f file2 -f file3 -o output_file

我知道这个简单的问题可以单独使用 cat 和重定向来解决。但我感兴趣的是,在 bash 中,我们如何可以获取所有三个 -f 参数并将它们放在一个数组中,以便我们可以对它们做点什么?

由于要求的性质,我们在这里需要某种形式的标志,因为会有其他参数。

在像 python 这样的语言中,这相当容易,尤其是对于像 docopt 这样的库。您可以按预期指定一个数组,然后就完成了。

非常感谢

【问题讨论】:

    标签: bash shell command-line command-line-arguments


    【解决方案1】:

    你可以使用getopts:

    #!/bin/bash
    
    while getopts "f:o:" opt; do
        case $opt in
            f) file+=("${OPTARG}") ;;
            o) output="${OPTARG}" ;;
            *) exit 1 ;;
        esac
    done
    shift $((OPTIND-1))
    
    echo "List of files: \"${file[@]}\""
    echo "Output: \"$output\""
    

    例如:

    $ bash test.sh -f 1 -f 2 -f three -o /dev/null
    List of files: "1 2 three"
    Output: "/dev/null" 
    

    所以我正在做的是将每个-f 标志的每次出现都添加到数组file 中,然后简单地打印它。至于-o,我只是将输入保存到变量output。其他任何事情都会导致 getopts 的 stderr 并退出:

    $ bash test.sh -w hi
    test.sh: illegal option -- w
    $ echo $?
    1                       
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多