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

标签 arrays bash loops interpolation

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

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

user@host:~/sandbox# ./script.sh first second third
$1 $2 $3

我希望它能回显 $1、$2 和 $3 不是“$1”的文本值

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

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

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

所以,目标是让

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

按照我的方式,$1,$2,$3 不会被插入,而只是被读取为文本字符串。

最佳答案

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

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

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

echo "$@"

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

如果你想保留你现有的方法,你需要使用indirection!:

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

echo "${args[@]}"

来自 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.

关于arrays - 根据参数数量在循环中创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15420790/

相关文章:

ios - 从 UICollectionView 中删除/删除选定的单元格会导致索引超出范围 [有时]

php - 函数仅返回 mysqli 查询结果的第一个数组值

linux - GNU Bash 3.2.25(1) 多个转义字符显示目录列表

macos - mac 中的终端错误

java - 循环自列表

python - 如何使用 python 数据修复翻转

php - 重组数组以将元素从第三个位置连接到数组末尾并存储为第三个元素

java - 修改: How to update multiple rows in java jdbc on duplicate value

linux - Bash脚本telnet连接+for循环

arrays - 在 Windows 批处理文件中循环