【问题标题】:In bash, how do I set a variable to encompass a variable number of command line arguments?在 bash 中,如何设置变量以包含可变数量的命令行参数?
【发布时间】:2016-05-12 20:00:19
【问题描述】:

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

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

但我想不通的是如何编写“附件”行来包含参数 #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”。

【问题讨论】:

  • 首先不要使用那些愚蠢的引号,其次获取前4个args然后shift 4attachments=( "$@" )

标签: bash shell command-line-arguments


【解决方案1】:

通常的做法是将固定的参数捕获到变量中,然后将剩余的作为"$@"提供:

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

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

如果您发现列表前面需要可变数量的参数,则此习惯用法很容易扩展:

while [ "${1#-}" != "$1" ]
do
    case "$1" in
      -foo) foo="$2";shift 2 ;;
      -bar) bar="$2";shift 2 ;;
      -baz) bar=true;shift 1 ;;
      --) shift; break;
    esac
done
# rest of arguments are in "$@"

【讨论】:

    【解决方案2】:
    srcdir=$1
    destdir=$2
    optflag=$3
    barflag=$4
    attachments=( "${@:5}" )
    

    【讨论】:

    • 我更喜欢这种方法,因为它不会与参数列表本身混淆。顺便说一句,您还可以从列表中间提取参数,例如"${@:5:3}" 将包含 3 个从 #5 开始的参数(即参数 5、6 和 7)
    猜你喜欢
    • 1970-01-01
    • 2013-08-02
    • 2019-11-06
    • 2011-10-16
    • 1970-01-01
    • 2017-09-18
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多