Ubuntu – Read file into array

bashcommand line

How can I read file in shell script , then assign each line to an variable that i can use later ,,,(am thinking in way to load an default setting from file)

i already try :

process (){

}

FILE=''
read -p "Please enter name of default file : " FILE

if [ ! -f $FILE  ]; then

    echo "$FILE : does not exists "
    exit 1
elif [ ! -r $FILE  ]; then

    echo "$FILE : can not read "
fi

exec 0<"$FILE"
n=0
while read -r line
do
   (assign each line to an variable) 
done

Best Answer

For configuration purposes it's probably easiest to define the parameters in the configuration file in bash syntax and later source it using . /path/to/config.

Example default.cfg:

parameter_a=100
parameter_b=200
parameter_c="Hello world"

Example script.sh:

#!/bin/bash

# source the default configuration
. /path/to/default.cfg

echo $parameter_a
echo $parameter_b
echo "$parameter_c"

...

If you don't like that approach you can also read the lines into an array:

while read line
do
    array+=("$line")
done < some_file

To access the items you would then use ${array[index]}, e.g.:

for ((i=0; i < ${#array[*]}; i++))
do
    echo "${array[i]}"
done

(Where ${#array[*]} is the size of the array.)

Read more about arrays in bash here.