bash shell environment-variables – Why is Setting a Variable Before a Command Legal in Bash?

bashenvironment-variablesshell

I've just encountered several answers such as to parsing a delimited text file… that use the construct:

while IFS=, read xx yy zz;do
    echo $xx $yy $zz
done < input_file

where the IFS variable is set before the read command.

I've been reading through the bash reference but can't figure out why this is legal.

I tried

$ x="once upon" y="a time" echo $x $y

from the bash command prompt but got nothing echoed. Can someone point me to where that syntax is defined in the reference that allows the IFS variable to be set in that way? Is it a special case or can I do something similar w/ other variables?

Best Answer

Relevant information can be found on the man page provided by the BASH maintainer (last checked August 2020). Section Shell Grammar, Simple Commands states (emphasis added):

A simple command is a sequence of optional variable assignments followed by blank-separated words and redirections, and terminated by a control operator. The first word specifies the command to be executed, and is passed as argument zero. The remaining words are passed as arguments to the invoked command.

So you can pass any variable you'd like. Your echo example does not work because the variables are passed to the command, not set in the shell. The shell expands $x and $y before invoking the command. This works, for example:

$ x="once upon" y="a time" bash -c 'echo $x $y'
once upon a time
Related Question