There are key a few key things that happen here:
As explained in bash reference manual, Simple Command Expansion, section "If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment." Thus, when you say
var="something" command arg1 arg2, the command will run withvarbeing in command's environment and disappearing aftercommandexits. Demonstration of this is simple - access the command's environment from within the command:$ BAZ="jake" python -c "import os; print os.environ['BAZ']" jakeThis is nothing to be surprised about. Such syntax is frequently used to run programs with modified environment. My fellow unix.stackexchange.com and askubuntu.com users will recognize this example: if user uses German locale, and you only speak in English, you can ask them to reproduce whatever issue they're having and obtain output in English like so:
LC_ALL=C commandNote also that environment access isn't specific to
python. It can be done withCor any other programming language. It just so happened to be my "weapon of choice" right now and only used for this demo.The variable expansion occurs before anything runs. Thus, when you run something like
BAZ="foo" echo $BAZ, the shell looks into its environment first, finds no variable BAZ there , and thus leaves$BAZempty. Simple demonstration of that is:$ BAZ="jake" python -c "import sys; print 'ARG:',sys.argv[1]" $BAZ ARG: Traceback (most recent call last): File "<string>", line 1, in <module> IndexError: list index out of range
It's important to also note, the distinction from BAZ=jake; echo $BAZ which is two separate command statements and here BAZ=jake will stay in shell's environment. The use case depends on your intentions. If you intend running more than one program that needs such variable, it might be desirable to export such variable. If you only need it for this one specific time, then preceding variable assignments are might be preferable.