如何在bash中为数组分配值? [英] How to assign a value to an array in bash?

查看:64
本文介绍了如何在bash中为数组分配值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to read a list of values from a text file hello.txt and store them in an array.

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语句不打印数组的内容。

I am not able to assign values to the array Unix_Array[].. The echo statement does not print the contents of the array.

推荐答案

此处存在一些语法错误,但很明显的问题是分配正在发生,但是您位于隐含的子外壳中。通过使用管道,您已经为整个while语句创建了一个子外壳。 while语句完成后,子shell退出,您的 Unix_Array 不再存在。

There are a few syntax errors here, but the clear problem is that the assignments are happening, but you're in an implied subshell. By using a pipe, you've created a subshell for the entire while statement. When the while statement is done the subshell exits and your Unix_Array ceases to exist.

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

In this case, the simplest fix is not to use a pipe:

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]}

顺便说一句,您真的不需要计数器。

By the way, you don't really need the counter. An easier way to write this might be:

$ 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

这篇关于如何在bash中为数组分配值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆