这里有一些语法错误,但明显的问题是分配正在发生,但你在隐含的 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