如何使用 getopts 处理多个输入文件参数

Maj*_*lik 2 bash arguments getopts

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

./script.sh -a sth -b sth - c sth -d sth input1 input2 input3    
Run Code Online (Sandbox Code Playgroud)

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

Pra*_*ord 5

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

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

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

如果您只想从 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
Run Code Online (Sandbox Code Playgroud)