This command:
A=456 echo a random following command
is similar to this command:
env A=456 echo a random following command
The new value 456
of A
will only be used for the echo
command. After the execution of the command echo
, the variable A
regains the original value.
The official document is Bash Reference Manual: Environment; as it explains:
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.
Update 0x00
When we run the following commands:
A=123
A=456 echo $A
The output is still 123
, not 456
. The reason is that Bash will evaluate $A
first before executing the command A=456 echo $A
. So the command:
A=456 echo $A
becomes
A=456 echo 123
And then we got the output 123
.
But the following example is different
A=123
A=456 eval echo '$A'
This output is 456
.
Because '$A'
is a plain string, Bash will not evaluate it before running the command. When the eval
command is running, the variable A
is set to 456
by Bash.
Update 0x01
A subshell is also a child process, but a variable which is not marked for export is still available for the subshell.
Bash Reference Manual: Command Execution Environment, as it explains:
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment
A=123
( eval echo \$A )
The output is 123
. Even we put (eval echo \$A)
into the background, the output is still 123
.
A=123
( eval echo \$A )&
When we execute a simple command, not a built-in or shell function, such as executing a script. This script is invoked in a separated shell environment. Only the shell variables marked for export are available for the separated environment.
A=123
bash -c 'echo A1=$A'
export A
bash -c 'echo A2=$A'
The output is:
A1=
A2=123