本文翻译自:Process all arguments except the first one (in a bash script)
I have a simple script where the first argument is reserved for the filename, and all other optional arguments should be passed to other parts of the script. 我有一个简单的脚本,其中第一个参数是为文件名保留的,所有其他可选参数应该传递给脚本的其他部分。
Using Google I found this wiki , but it provided a literal example: 使用Google我发现了这个wiki ,但它提供了一个文字示例:
echo "${@: -1}"
I can't get anything else to work, like: 我无法得到任何其他工作,例如:
echo "${@:2}"
or 要么
echo "${@:2,1}"
I get "Bad substitution" from the terminal. 我从终端得到“坏替换”。
What is the problem, and how can I process all but the first argument passed to a bash script? 问题是什么,除了传递给bash脚本的第一个参数外,我该如何处理?
#1楼
参考:https://stackoom.com/question/c0Et/处理除第一个之外的所有参数-在bash脚本中
#2楼
Use this: 用这个:
echo "${@:2}"
The following syntax: 以下语法:
echo "${*:2}"
would work as well, but is not recommended, because as @Gordon already explained, that using *
, it runs all of the arguments together as a single argument with spaces, while @
preserves the breaks between them (even if some of the arguments themselves contain spaces). 也可以工作,但不推荐,因为正如@Gordon已经解释的那样,使用*
,它将所有参数作为单个参数与空格一起运行,而@
保留它们之间的中断(即使一些参数本身包含空格)。 It doesn't make the difference with echo
, but it matters for many other commands. 它与echo
没有区别,但它对许多其他命令很重要。
#3楼
If you want a solution that also works in /bin/sh
try 如果你想要一个也适用于/bin/sh
的解决方案
first_arg="$1"
shift
echo First argument: "$first_arg"
echo Remaining arguments: "$@"
shift [n]
shifts the positional parameters n times. shift [n]
将位置参数移位n次。 A shift
sets the value of $1
to the value of $2
, the value of $2
to the value of $3
, and so on, decreasing the value of $#
by one. shift
将$1
的值设置为$2
的值, $2
的值设置为$3
,依此类推,将$#
的值$#
1。
#4楼
http://wiki.bash-hackers.org/scripting/posparams http://wiki.bash-hackers.org/scripting/posparams
It explains the use of shift
(if you want to discard the first N parameters) and then implementing Mass Usage 它解释了shift
的使用(如果你想丢弃前N个参数)然后实现批量使用