bash – get a list of environment variables with proper handling of new lines

Issue

$ export MYVAR=$(echo -e "something\nMYVAR=10")
$ env
...
MYVAR=something
MYVAR=10
...

The code above shows the problem.
If you try to read this using simplified version (and lots of people do it this way) you would will get wrong values. This explains it:

$ env | while IFS== read var value; do
    [ "$var" == "MYVAR" ] && echo $value
done
someting
10

After long investigation I am wondering if bash or sh is is simply not capable of handling this case.

If I could get just a list of variables without the values I could have it solved but looks like without an external task (python, for example) I can’t do it…

QUESTION: How, in shell, I can get a list of environment variables with their values that would work with the example above?

Solution

As choroba pointed out, you can use env -0 :

export MYVAR="$(echo -e "something\nMYVAR=10")"

env -0 | while IFS== read -d '' -r var value; do
    [ "$var" = "MYVAR" ] && echo "$value"
done
something
MYVAR=10

Answered By – Philippe

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published