bash中的参数循环
在bash中,我可以循环所有参数,$@。bash中的参数循环,bash,shell,Bash,Shell,在bash中,我可以循环所有参数,$@。 有没有办法获取当前参数的索引?(以便我可以引用下一个或上一个。)与您指定的不完全一样,但是您可以通过多种不同的方式迭代参数 例如: while test $# -gt 0 do echo $1 shift done 将位置参数复制到数组非常简单: $ set -- a b c d e # set some positional parameters $ args=("$@") # copy them into an
有没有办法获取当前参数的索引?(以便我可以引用下一个或上一个。)与您指定的不完全一样,但是您可以通过多种不同的方式迭代参数 例如:
while test $# -gt 0
do
echo $1
shift
done
将位置参数复制到数组非常简单:
$ set -- a b c d e # set some positional parameters
$ args=("$@") # copy them into an array
$ echo ${args[1]} # as we see, it's zero-based indexing
b
并且,迭代:
$ for ((i=0; i<${#args[@]}; i++)); do
echo "$i ${args[i]} ${args[i-1]} ${args[i+1]}"
done
0 a e b
1 b a c
2 c b d
3 d c e
4 e d
$for((i=0;i您可以循环参数编号,并使用间接展开(${!argnum}
)从中获取参数:
for ((i=1; i<=$#; i++)); do
next=$((i+1))
prev=$((i-1))
echo "Arg #$i='${!i}', prev='${!prev}', next='${!next}'"
done
for((i=1;这真是件好事,因为可以成对检查参数及其下一个参数(例如:--param value)。