6

What exactly is happening in the below bash incantation?

x=10 echo $x

I was under the impression that commands on bash can be chained using &&, || or ; but not simply separated by white-space. The above only works if the first command is an assignment. E.g. ls ls fails but foo=zoo ls works just fine.

A real case of the above style is found in this SO answer.

Marcus Junius Brutus
  • 4,587
  • 11
  • 44
  • 65

3 Answers3

4

That is a special syntactic construction to invoke a command with a variable set. It means that the scope of the variable is limited to that command.

For example, this command:

x=10 sh -c 'echo $x'

Is quite equivalent to this other command:

( export x=10; sh -c 'echo $x' )

The example you gave (x=10 echo $x) is not an appropiate example of this construction because the variable $x is evaluated before echo is invoked.

LatinSuD
  • 1,421
4

When you do:

var=value command

you had passed string var=value to the environment of command. This environment will be used when command is executed.

From bash - Environment documentation:

The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described in Shell Parameters. These assignment statements affect only the environment seen by that command.

But in your case, the command doesn't work. Because:

  • In most shells, echo is a builtin function, therefore will not executed.
  • $x had been expanded by the shell.
cuonglm
  • 153,898
3

Your command assets variable x to your value for the specific command you are running, instead of setting it in your shell. Local assignment so to say.

You can use this to either set or change an existing variable for one command.

Other uses I've used is

http_proxy=myproxy wget http://myurl

This will set a specific proxy for that particular url, without changing your shells default proxy setting.

LANG=C sort file

Sort your file based on a specific language setting, but only for that particular execution.

sastorsl
  • 336