0

Below I run what I expected to be an invalid command: var=3 date, which in fact isn't.

$ var=3 date
Sun May 26 17:10:22 UTC 2019
$ echo $?
0

But the variable wasn't assigned the value 3:

$ echo $var

$

I expected to say that var=3 wasn't a valid command. What am I missing?

1 Answers1

0

You are setting var to 3 as an environment variable in the environment of the date command, and not in the environment of the bash shell itself (the calling/parent process).

For refence, see the Bash manual at https://www.gnu.org/software/bash/manual/html_node/Environment.html

and specifically:

The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.

Edward
  • 2,509
  • Any chance you can find a source for dash or POSIX? Because my question is reproducible in dash. – Damn Spaces May 26 '19 at 17:43
  • It's also described in man dash, see Simple Commands section. – Arkadiusz Drabczyk May 26 '19 at 17:49
  • I'm not seeing that this is true in Bash. compgen -v gives us completion options of variables. Running var=3 compgen -v won't display var. – Damn Spaces May 26 '19 at 18:03
  • It is set in the environment of a subprocess. Try putting echo $var in a separate script called test.sh and calling var=3 ./test.sh. compgen is a builtin. Or, even better, put compgen -v in that script and you will see var pop up. – Edward May 26 '19 at 18:18