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!

One Response to “Shell variable assigment - a stupid bug”

  1. Pascal Bauermeister Says:

    The two forms are both valid and have really different meanings !

    This one:

    VAR=value command
    

    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.txt will tell ‘less’ to launch emacs upon pressing ‘v’.

    On the other hand, the second form

    VAR=value; command

    defines VAR for the remaining instance of the shell, but the shell will NOT pass it to subprocesses, so Z=hello; env will NOT display any Z variable, whereas Z=hello; echo $Z will display ‘hello’ (because of shell variable expansion).

    A third form is using ‘export’:

    export VAR=value; command

    . It is like the first form, but VAR will be passed to all subsequent commands.

    Cheers,

    Pascal

Leave a Reply