在 bash 中循环参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15696636/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:01:45  来源:igfitidea点击:

looping over arguments in bash

bashshell

提问by user2223066

In bash, I can loop over all arguments, $@. Is there a way to get the index of the current argument? (So that I can refer to the next one or the previous one.)

在 bash 中,我可以遍历所有参数 $@。有没有办法获得当前参数的索引?(这样我就可以参考下一个或上一个。)

回答by jedwards

Not exactly as you specify, but you can iterate over the arguments a number of different ways.

与您指定的不完全一样,但您可以通过多种不同的方式迭代参数。

For example:

例如:

while test $# -gt 0
do
    echo 
    shift
done

回答by glenn Hymanman

Pretty simple to copy the positional params to an array:

将位置参数复制到数组非常简单:

$ 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

And, iterating:

并且,迭代:

$ 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  

回答by Gordon Davisson

You can loop over the argument numbers, and use indirect expansion (${!argnum})to get the arguments from that:

您可以遍历参数编号,并使用间接扩展 ( ${!argnum}) 从中获取参数:

for ((i=1; i<=$#; i++)); do
    next=$((i+1))
    prev=$((i-1))
    echo "Arg #$i='${!i}', prev='${!prev}', next='${!next}'"
done

Note that $0(the "previous" argument to $1) will be something like "-bash", while the "next" argument after the last will come out blank.

请注意$0( 的“前一个”参数$1)将类似于“-bash”,而最后一个之后的“下一个”参数将显示为空白。