How to assign a value to an array in bash?

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

If you are using bash v4 or higher, you can use mapfile to accomplish this:

mapfile -t Unix_Array < hello.txt

Otherwise, this should work:

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

Tags:

Arrays

Shell

Bash