Question

I'm confused by this behaviour:

$ FOO=42 echo "$FOO"

$ FOO=42 && echo "$FOO"
42

I'm accustomed to using VARNAME=value cmd to specify environment variables for other commands, so I was surprised to discover it doesn't work when cmd is echo. This might have something to do with echo being a Bash built-in. Is this the case? If so, is using && the best way to specify environment variables for Bash built-ins?

Update: && is no good, as it results in the environment variables being set permanently, which I'm trying to avoid.

Was it helpful?

Solution

It doesn't matter that echo is a built-in. The reason is that variables on the command line are evaluated before executing the command, they're not evaluated by the command. You could get the result you want with:

FOO=42 bash -c 'echo "$FOO"'

This starts a new shell to execute echo $foo. Since the argument to bash is in single quotes, the variable is not replaced by the original shell.

OTHER TIPS

The replacement happens before the command is executed:

  1. $FOO is replaced with its current value.

  2. echo "" is executed with $FOO set to 42.

Try:

FOO=42 sh -c 'echo "$FOO"'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top