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?
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
Parameter expansions occur before the shell runs the command. So if
Acurrently has the value 3, the command line is first evaluated asand then the shell identifies what command is to be run (
env). At that pointenvconstructs a new environment whereAhas the value 42, then runs the commandecho 3in that environment.