Home > Net >  bash - get a list of environment variables with proper handling of new lines
bash - get a list of environment variables with proper handling of new lines

Time:09-21

$ 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?

CodePudding user response:

env only shows the exported environment.

compgen -A variable

will give you a list of all environment variables - including the variables not exported.

For each of these you can then run:

typeset -p "$@"

to get the full declaration.

Or you can get all declarations:

typeset -p

CodePudding user response:

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

CodePudding user response:

You can use awk to get just the names of the environment variables:

$ awk 'BEGIN {for (k in ENVIRON) { print k }}'
...

Since the names are guaranteed to be free of newlines, you can pipe this to your shell loop:

awk '...' | while read name; do
   value=${!name}
   ...
done

or do your processing in awk itself if possible.

(In bash, you can use declare -x to get output similar to what env produces. It would be nice if there was an additional flag you could use to get only the names of environment variables.)

CodePudding user response:

One simple way to see an environment variable without its name is to just echo it (inside a quoted string):

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

The environment variable contains a newline followed by "MYVAR=", making the output of "env" look a little strange, but it is working correctly.

  • Related