I'm trying to figure out, how the oneliner
var=value command
actually works in sh. I expect variable var
to be passed to the environment of command
, but shouldn't exist in the current environment (please, do not omit disclaimer at the end!)
First, let's try it in bash
#bash
$ var= #just to be sure it's empty
$ var=value echo something
. something
$ echo "$var"
.
$ var=value set something
$ echo "$var"
.
For now, it works as expected. But when we go to sh and retype the same input, it'll be like that:
#sh
$ var=
$ var=value echo something
. something
$ echo "$var"
.
$ var=value set something
$ echo "$var"
. value
And the last one differs. Is set
command some kind of special case for sh? Why has the variable var
been saved in our current environment?
disclaimer: I know that echo
and set
are shell built-in's and thus environment variables we pass them by var=value command
are wasted, but my question is about the syntax only. I mean, they should have been wasted, but in sh, when typed set
, the variable was somehow passed into the current environment.
set
is a "special" built-in, defined as such in the POSIX specification.
As described in Simple Commands, variable assignments preceding the invocation of a special built-in utility remain in effect after the built-in completes; this shall not be the case with a regular built-in or other utility.
So in this case, bash
is actually in violation of the POSIX specification. Running in POSIX mode, though, it behaves the same as sh
:
$ bash --posix
$ var=value set something
$ echo $var
value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With