如何在bash脚本中省略某些输入变量(如$ 1和$ 2)时使用$ *?

例如,

elif [[ $append = $1 ]] then touch ~/directory/"$2".txt echo "$variable_in_question" >> ~/directory/"$2".txt 

要么创建一个包含"$2"之后的所有输入的文本文件,要么附加一个包含"$2"之后的所有输入的现有文本文件,我将使用什么代替第4行中的"$variable_in_question"

我基本上想要"$*" ,但省略"$1""$2"

您可以使用bash参数扩展来指定范围,这也适用于位置参数。 $3$n它将是:

 "${@:3}" # expands to "$3" "$4" "$5" … "${*:3}" # expands to "$3 $4 $5 …" 

请注意, $@$*忽略第一个参数$0 。 如果你想知道在你的情况下使用哪一个:你可能想要一个引用的$@ 。 除非您明确希望单独引用参数,否则不要使用$*

你可以尝试如下:

 $ bash -c 'echo "${@:3}"' 0 1 2 3 4 5 6 3 4 5 6 $ echo 'echo "${@:3}"' >script_file $ bash script_file 0 1 2 3 4 5 6 2 3 4 5 6 

请注意,在第一个示例中, $0填充了第一个参数0而在脚本中使用$0则填充了脚本的名称,如第二个示例所示。 bash的脚本名称当然第一个参数,只是它通常不会被认为是这样 – 对于一个可执行的脚本和“直接”调用的脚本也是如此。 所以在第一个例子中我们有$0 = 0$1 = 1等等,而在第二个例子中它是$0 = script_file$1 = 0$2 = 1等; ${@:3}选择以$3开头的每个参数。

可能范围的一些其他示例:

  # two arguments starting with the third $ bash -c 'echo "${@:3:2}"' 0 1 2 3 4 5 6 3 4 # every argument starting with the second to last one # a negative value needs either a preceding space or parentheses $ bash -c 'echo "${@: -2}"' 0 1 2 3 4 5 6 5 6 # two arguments starting with the fifth to last one $ bash -c 'echo "${@:(-5):2}"' 0 1 2 3 4 5 6 2 3 

进一步阅读:

  • man bash / EXPANSION /参数扩展
  • bash-hackers.org:处理位置参数
  • TLDP Advanced Bash-Scripting Guide:参数替换

你可以使用shift内置:

 $ help shift shift: shift [n] Shift positional parameters. Rename the positional parameters $N+1,$N+2 ... to $1,$2 ... If N is not given, it is assumed to be 1. Exit Status: Returns success unless N is negative or greater than $#. 

防爆。 特定

 $ cat argtest.bash #!/bin/bash shift 2 echo "$*" 

然后

 $ ./argtest.bash foo bar baz bam boo baz bam boo 

通常,您可以将位置参数复制到数组,删除数组的任意索引,然后使用数组扩展到您想要的那些索引,而不会丢失原始参数。

例如,如果我想要除第一个,第四个和第五个之外的所有参数:

 args=( "$@" ) unset args[0] args[3] args[4] echo "${args[@]}" 

在副本中,索引移位1,因为$0不是$@一部分。