1

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

5
  • What do you want to execute? ./test: line 4: folder=abc: command not found means that there execution occurred, but failed, as there was no such an application. Really hard to tell what are you asking about. Commented Apr 21, 2019 at 7:40
  • 2
    You seem to be set up to discover eval, then (hopefully sooner than later) concluding that redefining your problem is probably better than actually using eval. Commented Apr 21, 2019 at 7:51
  • @Flash Thunder, I was trying to set the variable "folder" to "abc" Commented Apr 21, 2019 at 11:35
  • 1
    @oguz ismail, That does the trick for what I want and is easy to follow Commented Apr 21, 2019 at 11:38
  • @Poshi, Thanks, it looks like it works, but to my untrained eye, oguz ismail's solution seems easier to read. Commented Apr 21, 2019 at 11:38

4 Answers 4

3

for your sample, declare is the safest option:

while read -r line; do
  declare "$line"
done
$ echo "$folder"
abc
$ echo "$name"
xyz
Sign up to request clarification or add additional context in comments.

Comments

1

Direct approach, use eval.

Different approach, try with source or .:

$ echo "$line"
folder=abc
$ . <(echo "$line")
$ echo "$folder"
abc

But probably the good answer will be to tackle the problem in a different way.

2 Comments

eval is your friend
"With friends like this, who needs enemies?"
0

You can clean up your approach a bit without resorting to eval.

while IFS="=" read -r name value; do
    case $name in
        folder) folder=$value ;;
        name) name=$value ;;
    esac
done < /etc/testfile.conf

Comments

0

why not only source de file ?

$ . infile ; echo "$name"
xyz

1 Comment

The file is actually somewhat more complicated. Divided into sections with xml type tags, and I only want a couple of values from each section. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.