Answer the question
In order to leave comments, you need to log in
How to assign the value of an element of a string array in bash?
The question is, there are string arrays in bash, you can assign an array element through array["$i"]=. For example, I do so that the lines from the array.list file are written to the string array array, and then displayed ... and it does not work. Where is the mistake?
#!/bin/bash
i=1
cat array.list | while read str
do
array["$i"]="$str"
i=$(($i+1))
done
echo ${array[@]}
Answer the question
In order to leave comments, you need to log in
Well, I did a Google search for you:
bash set array element
Enjoy:
declare -a array
In your case cat array | while runs the entire while block in a separate shell process, and naturally the result will not be returned to the parent process, dying along with the end of the loop and the child process.
Do like this:
#!/bin/bash
i=1
while read str
do
array["$i"]="$str"
i=$(($i+1))
done <array.list
echo ${array[@]}
you can drive lines from a file into an array much easier:
x="$IFS";IFS=$'\n';array=(`cat array.list`);IFS="$x"
i=1
shopt -s lastpipe
cat array.list | while read str
do
array["$i"]="$str"
i=$(($i+1))
done
shopt -u lastpipe
echo ${array[@]}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question