在 bash 中,如何设置变量以包含可变数量的命令行参数?

In bash, how do I set a variable to encompass a variable number of command line arguments?

我正在使用 bash shell。我正在编写一个脚本,我想在参数 #5 之后(包括参数 #5)捕获传递给我脚本的可变数量的参数。到目前为止我有这个......

#!/bin/bash
…
declare -a attachments
attachments=( "" )

但我想不通的是如何编写“附件”行来包含参数 #5 以及后面的任何参数。所以在下面的例子中

sh my_script.sh arg1 arg2 arg3 arg4 “my_file1.csv” “my_file2.csv”

我希望附件由“my_file1.csv”和“my_file2.csv”组成,而在此示例中......

sh my_script.sh arg1 arg2 arg3 arg4 “my_file1.csv” “my_file2.csv” “my_file3.csv”

我希望附件包含“my_file1.csv”、“my_file2.csv”和“my_file3.csv”。

通常的习惯用法是将固定的参数捕获到变量中,然后剩余的可用"$@":

srcdir=""; shift
destdir=""; shift
optflag=""; shift
barflag=""; shift

(cd "$destdir" && mv -t "$destdir" "-$optflag" "$@" )

如果您发现需要在列表之前使用可变数量的参数,这个习惯用法很容易扩展:

while [ "${1#-}" != "" ]
do
    case "" in
      -foo) foo="";shift 2 ;;
      -bar) bar="";shift 2 ;;
      -baz) bar=true;shift 1 ;;
      --) shift; break;
    esac
done
# rest of arguments are in "$@"
srcdir=
destdir=
optflag=
barflag=
attachments=( "${@:5}" )