Unix: Why doesn't env A=42 echo ${A} work?

75 views Asked by At

The env man page says that it'll set the specified environment variables and then run the specified command. Knowing that, I'd expect

env A=42 echo ${A}

to print 42, but it shows nothing instead. What am I doing wrong?

2

There are 2 answers

0
chepner On BEST ANSWER

Parameter expansions occur before the shell runs the command. So if A currently has the value 3, the command line is first evaluated as

env A=42 echo 3

and then the shell identifies what command is to be run (env). At that point env constructs a new environment where A has the value 42, then runs the command echo 3 in that environment.

2
Reut Sharabani On

This is because ${A} is evaluated before echo is executed. This means echo gets an argument with the value of A in the previous environment (no value...).

One solution is to pass the parameter as a literal string (single quote) to be expanded at a later stage along with echo:

user@host:~$ env A=42 bash -c 'echo ${A}'
42