bash 根据参数数量在循环中创建数组

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

Create array in loop from number of arguments

arraysbashloopsinterpolation

提问by parsecpython

#!/bin/bash
COUNTER=$#
until [ $COUNTER -eq 0 ]; do
args[$COUNTER]=$$COUNTER
let COUNTER-=1
done
echo ${args[@]}

When i run this, I get the following results

当我运行它时,我得到以下结果

user@host:~/sandbox# ./script.sh first second third
  

and i'm expecting it to echo out what $1, $2, and $3 are not a text value of "$1"

我期待它回显出 $1、$2 和 $3 不是“$1”的文本值

I'm trying to write a script in bash that will create an array that is the size of the number of arguments I give it.
I'm expecting

我正在尝试在 bash 中编写一个脚本,该脚本将创建一个数组,该数组的大小与我提供的参数数量相同。
我期待着

user@host:~/sandbox# ./script.sh alpha bravo charlie
alpha bravo charlie

or

或者

user@host:~/sandbox# ./script.sh 23425 jasson orange green verb noun coffee
23425 jasson orange green verb noun coffee

So, the goal is to make

所以,目标是使

args[0]=
args[1]=
args[2]=
args[3]=

The way that I have it, the $1,$2,$3aren't being interpolated but just being read as a text string.

我拥有它的$1,$2,$3方式不是被插值,而是被作为文本字符串读取。

回答by jordanm

You can use the +=operator to append to an array.

您可以使用+=运算符附加到数组。

args=()
for i in "$@"; do
    args+=("$i")
done
echo "${args[@]}"

This shows how appending can be done, but the easiest way to get your desired results is:

这显示了如何进行附加,但获得所需结果的最简单方法是:

echo "$@"

or

或者

args=("$@")
echo "${args[@]}"

If you want to keep your existing method, you need to use indirectionwith !:

如果你想保持现有的方法中,你需要使用间接使用!

args=()
for ((i=1; i<=$#; i++)); do
   args[i]=${!i}
done

echo "${args[@]}"

From the Bash reference:

从 Bash 参考:

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix } and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

如果参数的第一个字符是感叹号 (!),则引入了一个变量间接级别。Bash 使用由参数的其余部分形成的变量的值作为变量的名称;这个变量然后被扩展,并且该值用于替换的其余部分,而不是参数本身的值。这称为间接扩展。例外情况是下面描述的 ${!prefix } 和 ${!name[@]} 的扩展。感叹号必须紧跟在左大括号之后才能引入间接性。