Richard C
Richard C

Reputation: 411

Open file with two columns and dynamically create variables

I'm wondering if anyone can help. I've not managed to find much in the way of examples and I'm not sure where to start coding wise either.

I have a file with the following contents...

VarA=/path/to/a
VarB=/path/to/b
VarC=/path/to/c
VarD=description of program
...

The columns are delimited by the '=' and some of the items in the 2nd column may contain gaps as they aren't just paths.

Ideally I'd love to open this in my script once and store the first column as the variable and the second as the value, for example...

echo $VarA
...
/path/to/a


echo $VarB
...
/path/to/a

Is this possible or am I living in a fairy land?

Thanks

Upvotes: 0

Views: 48

Answers (3)

anubhava
anubhava

Reputation: 785631

A minus sign or a special character isn't allowed in a variable name in Unix.

You may consider using BASH associative array for storing key and value together:

# declare an associative array
declare -A arr

# read file and populate the associative array
while IFS== read -r k v; do
   arr["$k"]="$v"
done < file

# check output of our array
declare -p arr
declare -A arr='([VarA]="/path/to/a" [VarC]="/path/to/c" [VarB]="/path/to/b" [VarD]="description of program" )'

Upvotes: 1

chepner
chepner

Reputation: 531888

You might be able to use the following loop:

while IFS== read -r name value; do
    declare "$name=$value"
done < file.txt

Note, though, that a line like foo="3 5" would include the quotes in the value of the variable foo.

Upvotes: 1

Reut Sharabani
Reut Sharabani

Reputation: 31339

What about source my-file? It won't work with spaces though, but will work for what you've shared. This is an example:

reut@reut-home:~$ cat src 
test=123
test2=abc/def
reut@reut-home:~$ echo $test $test2

reut@reut-home:~$ source src
reut@reut-home:~$ echo $test $test2
123 abc/def

Upvotes: -1

Related Questions