gpt4 book ai didi

arrays - 如何在 Bash 中为数组赋值?

转载 作者:行者123 更新时间:2023-11-29 09:01:36 30 4
gpt4 key购买 nike

我正在尝试从文本文件 hello.txt 中读取值列表,并将它们存储在数组中。

counter=0

cat hello.txt | while read line; do
${Unix_Array[${counter}]}=$line;
let counter=counter+1;
echo $counter;
done

echo ${Unix_Array[0]}
echo ${Unix_Array[1]}
echo ${Unix_Array[2]}

我无法为数组 Unix_Array[] 赋值...echo 语句不打印数组的内容。

最佳答案

这里有一些语法错误,但明显的问题是分配正在发生,但是 you're in an implied subshell .通过使用管道,您已经为整个 while 语句创建了一个子 shell。当 while 语句完成时,子 shell 退出并且您的 Unix_Array 不复存在。

在这种情况下,最简单的解决方法是不使用管道:

counter=0

while read line; do
Unix_Array[$counter]=$line;
let counter=counter+1;
echo $counter;
done < hello.txt

echo ${Unix_Array[0]}
echo ${Unix_Array[1]}
echo ${Unix_Array[2]}

顺便说一句,你真的不需要计数器。一个更简单的写法可能是:

$ oIFS="$IFS" # Save the old input field separator
$ IFS=$'\n' # Set the IFS to a newline
$ some_array=($(<hello.txt)) # Splitting on newlines, assign the entire file to an array
$ echo "${some_array[2]}" # Get the third element of the array
c
$ echo "${#some_array[@]}" # Get the length of the array
4

关于arrays - 如何在 Bash 中为数组赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11087918/

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