Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: assignment of variable on same line not altering echo behavior [duplicate]

Tags:

bash

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.

like image 275
user5803214 Avatar asked Mar 24 '26 11:03

user5803214


1 Answers

$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.

like image 188
Biffen Avatar answered Mar 27 '26 03:03

Biffen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!