简体   繁体   English

如何在bash中为数组赋值?

[英]How to assign a value to an array in bash?

I am trying to read a list of values from a text file hello.txt and store them in an array.我正在尝试从文本文件 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]}

I am not able to assign values to the array Unix_Array[].. The echo statement does not print the contents of the array.我无法为数组 Unix_Array[] 赋值。 echo 语句不打印数组的内容。

There are a few syntax errors here, but the clear problem is that the assignments are happening, but you're in an implied subshell .这里有一些语法错误,但明显的问题是分配正在发生,但您处于隐含的 subshel​​l 中 By using a pipe, you've created a subshell for the entire while statement.通过使用管道,您已经为整个 while 语句创建了一个子 shell。 When the while statement is done the subshell exits and your Unix_Array ceases to exist.当 while 语句完成时,子shell 退出并且您的Unix_Array不复存在。

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

If you are using bash v4 or higher, you can use mapfile to accomplish this:如果您使用的是 bash v4 或更高版本,则可以使用mapfile来完成此操作:

mapfile -t Unix_Array < hello.txt

Otherwise, this should work:否则,这应该有效:

while read -r line; do
   Unix_Array+=("$line")
done < hello.txt

The best way I found is:我发现的最好方法是:

declare -A JUPYTER_VENV
JUPYTER_VENV=(test1 test2 test3)

And then consume it with:然后使用它:

for jupenv in "${JUPYTER_ENV[@]}"
do
  echo "$jupenv"
done

Instead of this:取而代之的是:

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

You can just do this:你可以这样做:

Unix_Array=( `cat "hello.txt" `)

Its a solution:它的一个解决方案:

count=0
Unix_Array=($(cat hello.txt))
array_size=$(cat hello.txt | wc -l)
for ((count=0; count < array_size; count++))
do
    echo ${Unix_Array[$count]}
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM