【问题标题】:How to handle multiple input file arguments using getopts如何使用 getopts 处理多个输入文件参数
【发布时间】:2014-04-29 09:02:35
【问题描述】:

我正在尝试为多个输入数据文件制作脚本。最好的方法是什么,如何处理这些论点?脚本的用法应该是:

./script.sh -a sth -b sth - c sth -d sth input1 input2 input3    

我可以使用 getopts 处理参数和参数,但我不知道如何处理这些输入文件,因为它们没有标志。 谢谢

【问题讨论】:

    标签: bash arguments getopts


    【解决方案1】:
    while getopts ":a:b:c:d:" opt; do
      case "$opt" in
        a) i=$OPTARG ;;
        b) j=$OPTARG ;;
        c) k=$OPTARG ;;
        d) l=$OPTARG ;;
      esac
    done
    shift $(( OPTIND - 1 ))
    
    
    for file in "$@"; do
      # your stuff here
    done
    

    请试试这个,这可能会解决你的目的

    我自己的评论促使我扩展答案:

    如果您想仅通过 getopts 进行操作: 您必须将脚本称为

    ./script -a hj -b op -c zx -d some -f "File in list seperated with spaces"

    while getopts ":a:b:c:d:f:" opt; do
      case "$opt" in
        a) i=$OPTARG ;;
        b) j=$OPTARG ;;
        c) k=$OPTARG ;;
        d) l=$OPTARG ;;
        f) files=$OPTARG ;;
      esac
    done
                          #no shift is required now, since we have file list in $files
    for file in $files; do
      # your stuff here
    done
    

    【讨论】:

    • 这正是我想要的,谢谢。我可以请您解释一下,它是如何工作的吗?我理解这种转变,但我不知道“文件循环”是如何工作的(怎么可能,它忽略其他参数并只查找最后一个参数)?
    • 实际上没有,根据您的问题,您正在寻找处理来自 getopts 的所有内容,我添加了一个额外的 for loop :)。解释部分:阅读转移 cmdline 参数(shift $(( OPTIND - 1 ))),您将了解$@ 如何只获得您想要的文件。
    • 我不推荐第二个版本,因为它无法处理文件名中包含空格或某些其他字符的文件。让getopts 处理选项,将非可选参数留在$@ 中以供以后处理。
    • 是的,但它可以派上用场,脚本有两个这样的参数要求像script -d some1 -f something -p "list of files" -j "list of files"这样的列表
    猜你喜欢
    • 2019-02-18
    • 2010-11-10
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多