a=2
a=3 echo $a #prints 2
can someone explain why would anyone use the above code in line-2. a=3 will be ignored as there is no "enter" after it. But I saw it in script like above and not sure about the purpose.
a=2
a=3 echo $a #prints 2
can someone explain why would anyone use the above code in line-2. a=3 will be ignored as there is no "enter" after it. But I saw it in script like above and not sure about the purpose.
$a
is expanded by the shell (Bash) before a=3
is evaluated. So echo
sees its argument as 2
, which is what it prints. (If you set -x
you can see that what gets executed is a=3 echo 2
.)
var=val command
is used to set an environment variable to be seen by command
during its execution, but nowhere else. So when command
reads environment variables (e.g. using getenv()
), to it $var
is val
.
If echo
were to look up $a
while running, it would have the value 3
.
The parent process expands a
before the environment is setup in which it sets a different value (3) for a
. Despite the fact that variable a
set to 3
by the echo
executes, the value was expanded already. So it's too late.
You can instead do:
a=3 bash -c 'echo $a'