以编程方式循环传递给脚本或函数的参数

Programatically cycle through arguments given to a script or function

我正在尝试循环遍历给 bash 脚本(或其中的函数)的未知数量的参数,以有效地处理可能性(</code>、<code>、等)甚至(</code>、<code> 等)以不同的方式。

我知道我可以使用 $# 获取参数的数量,使用 $@ 获取参数本身,当然 echo printf '%s\n' "" 都可以。我需要做的是用一个未知的数字有效地回应赔率 echo ...,然后分别处理偶数,并单独计算这些字符,所以如果可能的话,需要以编程方式获取这些字符。

注意:有些输入会有空格,但where总会有引号。一个例子是 1 "This one" "Another one" "and another" "last one".

我试过了(这些只是为了简洁起见得到输出):

在 for 和 while 安排中将 $@ 放入其自身的数组中(理解这个零索引数组):

indexedarray="$@"
for i in {0..$#..2}; do #This in itself creates an error ({0..5..2}: syntax error: operand expected (error token is "{0..5..2}")).
  echo -n "${indexedarray[$i]}
done

这会产生空输出:

i=0
while [ $i -lt $# ]; do
    echo ${INDEXEDARRAY[i]}
    ((i+2))
done

以及 for 或 while 循环中的(有点)明显的弱点:

  echo "${$@[$i]}"
  echo $"${i}"

None 其中有效。

关于如何改进它并获得我需要的输出有什么想法吗?

您似乎想打印所有其他参数。这里有一些方法。

我最喜欢的(尽管有点老套):

printf '%s\n%.0s' "$@"

下一个合乎逻辑的方法

while (($# > 0)); do
  echo ""
  shift
  shift
  # `shift 2` won't shift if there is only one argument left
done

以及最通用的方法

a=("$@")
for ((i=0; i<$#; i+=2)); do
  echo "${a[i]}"
done