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.

0

3 Answers 3

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.

3
  • Thanks, but where is this mentioned in the bash manual?
    – flow2k
    Jul 2, 2018 at 21:00
  • I can't find it there. I learned it by seeing it in a lot of scripts.
    – LatinSuD
    Jul 3, 2018 at 6:56
  • Actually there is a link in cuonglm's answer...
    – flow2k
    Jul 3, 2018 at 21:17
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.
3
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.