Search code examples
bashvariablesexecute

Bash - How can I execute a variable


I am reading a file with lines like:

folder=abc
name=xyz

For some lines line I would like set a variable e.g name=xyz corresponding to the line I have read.

Cutting it down, with name=xyz and folder=abc, I have tried:

while read -r line; do
    $line
    echo $name
done < /etc/testfile.conf

This gives an error message ./test: line 4: folder=abc: command not found etc.

I have tried "$line" and $($line) and it is the same. Is it possible to do what I whant?

I have succeeded by doing:

while read -r line; do
    if [[ "$line" == 'folder'* ]]; then
        folder="$(echo "$line" | cut -d'=' -f 2)"
    fi
    if [[ "$line" == 'name'* ]]; then
        name="$(echo "$line" | cut -d'=' -f 2)"
    fi
done < /etc/testfile.conf

but this seems messy


Solution

  • for your sample, declare is the safest option:

    while read -r line; do
      declare "$line"
    done
    
    $ echo "$folder"
    abc
    $ echo "$name"
    xyz