Search code examples
basheval

How to print / echo environment variables?


How do I print the environment variable just being set?

NAME=sam echo "$NAME" # empty

You can see here using eval it works. Is this the way?

NAME=sam eval 'echo $NAME' # => sam

Solution

  • These need to go as different commands e.g.:

    NAME=sam; echo "$NAME"
    NAME=sam && echo "$NAME"
    

    The expansion $NAME to empty string is done by the shell earlier, before running echo, so at the time the NAME variable is passed to the echo command's environment, the expansion is already done (to null string).

    To get the same result in one command:

    NAME=sam printenv NAME