gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:44:19 26 4
gpt4 key购买 nike

#!/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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com