> a=b echo hi
> echo $a // why this command does not print 'b'?
The a=b parameter assignment effects the environment for the echo command on the first line.
In another post, a user was having a problem opening a password protected pdf file. The poster knew the password, but it wasn't accepted. The solution was to change the local that the pdf reader program used by changing the LC_LOCALE variable on the same line preceding the command.
From 3.7.4 of the bash info manual:
The environment for any simple command or function may be augmented
temporarily by prefixing it with parameter assignments, as described in
*Note Shell Parameters::. These assignment statements affect only the
environment seen by that command.
Try this out:
Also look at:
( a=5; echo $a )
However, try these as well; can you figure out the difference?:
$ cat test2
$ a=3 ./test2
$ echo $a
# Maybe you weren't expecting the following
$ a=20 echo $a
# Here is a trick to use to see shell parameter expansion at work:
set a=20 echo $a
$ echo -e "$1\t$2\t$3\n"
/bin/bash a=5 echo 10
As you can see, the $a argument is expanded before the line is run. So it is a constant before bash assigns a=5 to the environment of echo.
$ testvar=10 env | grep testvar
The env command lists the environment variables.