문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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"'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top