作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试从文本文件 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/
我是一名优秀的程序员,十分优秀!