bash 遍历参数跳过第一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3575793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through parameters skipping the first
提问by piet
Hi i have the following:
嗨,我有以下几点:
bash_script parm1 a b c d ..n
I want to iterate and print all the values in the command line starting from a, not from parm1
我想从 a 开始迭代并打印命令行中的所有值,而不是从 parm1
采纳答案by Scharron
This should do it:
这应该这样做:
#ignore first parm1
shift
# iterate
while test ${#} -gt 0
do
echo
shift
done
回答by Ismail Badawi
You can "slice" arrays in bash; instead of using shift
, you might use
你可以在 bash 中“切片”数组;而不是使用shift
,你可以使用
for i in "${@:2}"
do
echo "$i"
done
$@
is an array of all the command line arguments, ${@:2}
is the same array less the first element. The double-quotes ensure correct whitespace handling.
$@
是所有命令行参数${@:2}
的数组,是同一个数组减去第一个元素。双引号确保正确的空格处理。
回答by ghostdog74
This method will keep the first param, in case you want to use it later
此方法将保留第一个参数,以防您以后想使用它
#!/bin/bash
for ((i=2;i<=$#;i++))
do
echo ${!i}
done
or
或者
for i in ${*:2} #or use $@
do
echo $i
done
回答by Paused until further notice.
You can use an implicit iteration for the positional parameters:
您可以对位置参数使用隐式迭代:
shift
for arg
do
something_with $arg
done
As you can see, you don't have to include "$@"
in the for
statement.
如您所见,您不必包含"$@"
在for
语句中。
回答by e2-e4
Another flavor, a bit shorter that keeps the arguments list
另一种风格,稍微短一点,可以保留参数列表
shift
for i in "$@"
do
echo $i
done