Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line setting environment variable and execute command, got different results in sh and bash

Tags:

linux

bash

shell

sh

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.

like image 804
Radosław Panuszewski Avatar asked Dec 20 '17 02:12

Radosław Panuszewski


Video Answer


1 Answers

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
like image 76
chepner Avatar answered Nov 15 '22 04:11

chepner