3 ms·
As a regular shell user I find this quite surprising. The article omits the important point that the shell variable persists after the conditional expression:
by rwmj 6y ago
As a regular shell user I find this quite surprising. The article omits the important point that the shell variable persists after the conditional expression:
$ foo= ; if foo=bar; then echo $foo ; fi ; echo $foo
bar
bar
However this work as expected. foo is only set as an environment variable for the duration of the command (true) in the condition.
$ foo= ; if foo=bar true; then echo $foo ; fi ; echo $foo
(prints two blank lines)
(My examples above use bash rather than the plain Bourne shell).
Now I'm wondering if the shell special-cases this.
Edit: No it doesn't. It just executes the command as normal using execute_command in the same context as the "if" statement, so any assignments take effect in the script, not in any sub-context. https://git.savannah.gnu.org/cgit/bash.git/tree/execute_cmd.c#n3686 https://git.savannah.gnu.org/cgit/bash.git/tree/execute_cmd....