Shell variable assigment - a stupid bug
I recently made a really stupid mistake. I wanted to do a simple variable assignment and run a command. What I did was the following:
VAR=value command $VAR
Obviously, this doesn’t work! As this is a single command, the shell does variable expansion before the assignment takes place, so the variable is null (or whatever it was before). Obviously, the variable is set correctly within the command’s execution environment, but it’s too late then
What I should have done in this case was:
VAR=value; command $VAR
Sadly, the command did not complain about my mistake and I only realized it after a lost night of computation. Phew!
October 12th, 2007 at 9:11 pm
The two forms are both valid and have really different meanings !
This one:
will define VAR for the scope of ‘command’ only (and will make VAR known to ‘command’). But, as you noticed, the shell does variables expansion before the assignment. For instance, doing
EDITOR=emacs less file.txtwill tell ‘less’ to launch emacs upon pressing ‘v’.On the other hand, the second form
defines VAR for the remaining instance of the shell, but the shell will NOT pass it to subprocesses, so
Z=hello; envwill NOT display any Z variable, whereasZ=hello; echo $Zwill display ‘hello’ (because of shell variable expansion).A third form is using ‘export’:
. It is like the first form, but VAR will be passed to all subsequent commands.
Cheers,
Pascal