How can we assign value to an array variable from an external file?

is it possible to assign value to an array variable from an external file?? if yes then how??

I am using below code but its not working.

#!bin/bash
myarray[1] < file_name
echo ${mayarray[1]}

You read with the read command.

read var[1] < file
1 Like

use declare -a as per bash manual
For example, here is a script that places first thre fields in three array elements

 
declare -a arr
while read arr[1] arr[2] arr[3];
do
        echo "arr[1]="${arr[1]}
        echo "arr[2]="${arr[2]}
        echo "arr[3]="${arr[3]}
done < $1

my input file:

1 2 3 4 5
11 22 33 44 55

the output of the script :

 
!x.sh zz
arr[1]=1
arr[2]=2
arr[3]=3 4 5
arr[1]=11
arr[2]=22
arr[3]=33 44 55

Note how 'unassigned 4th and 5th imput fields are bundled into last argument to read

1 Like

suppose my files contains 5 different values separated by newline some what like

cat file
value1
value2
value3
value4
value5

what script should I use to assign these value to different element of an array variable.

in bash, you can do:

readarray ARRAY < file

Its not working.Script that I am using is

#!bin/bash
readarray myarray < sample
echo ${myarray[*]}

where sample is a file :

cat sample
value1
value2
value3

Firstly, you need to specify a correct shebang:

#!/bin/bash

Secondly, mapfile AKA readarray can only be used in bash 4, so check with

/bin/bash --version

--
Alternatively you could use:

myarray=( $(<sample) )
1 Like