Bash + read variables & values from file by bash script

bashevallinuxshell-scriptvariable

I have the following file variable and values

# more file.txt
export worker01="sdg sdh sdi sdj sdk"
export worker02="sdg sdh sdi sdj sdm"
export worker03="sdg sdh sdi sdj sdf"

I perform source in order to read the variable

# source file.txt

example:

echo $worker01
sdg sdh sdi sdj sdk

until now every thing is perfect

but now I want to read the variables from the file and print the values
by simple bash loop I will read the second field and try to print value of the variable

#  for i in ` sed s'/=/ /g'  /tmp/file.txt | awk '{print $2}' `
   do  
   echo $i
   declare var="$i"
   echo $var
   done

but its print only the variable and not the values

worker01
worker01
worker02
worker02
worker03
worker03

expected output:

worker01
sdg sdh sdi sdj sdk
worker02
sdg sdh sdi sdj sdm
worker03
sdg sdh sdi sdj sdf

Best Answer

You have export worker01="sdg sdh sdi sdj sdk", then you replace = with a space to get export worker01 "sdg sdh sdi sdj sdk". The space separated fields in that are export, worker01, "sdg, sdh, etc.

It's probably better to split on =, and remove the quotes, so with just the shell:

$ while IFS== read -r key val ; do
    val=${val%\"}; val=${val#\"}; key=${key#export };
    echo "$key = $val";
  done < vars
worker01 = sdg sdh sdi sdj sdk
worker02 = sdg sdh sdi sdj sdm
worker03 = sdg sdh sdi sdj sdf

key contains the variable name, val the value. Of course this doesn't actually parse the input, it just removes the double quotes if they happen to be there.

Related Question