2

If I type the following command in a bash shell:

STUFF=Blah env | grep STUFF

I am confused why it would return STUFF=Blah as I would expect to get an empty output.

The reason I am confused is because (as I understand) STUFF=Blah sets STUFF as a shell variable, but the env command returns all environment variables.

But in the above STUFF=Blah seems to be set as an environment variable. Where am I going wrong in my understanding?

2 Answers 2

5

From the bash man page (ENVIRONMENT section):

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

This means that your understanding of the STUFF=Blah at the start of a command is incorrect. When using before a command, it sets an environment variable for the command being run. When used by itself (just STUFF=Blah without any further command), then it sets a local shell variable.

Sign up to request clarification or add additional context in comments.

1 Comment

And because it only affects the immediately following command, it wouldn't be useful for it to set a shell variable.
4

Prefixing a command with a variable assignment causes that command to run in an environment where that variable is set. The env command sees STUFF set to Blah in its environment, but not the current shell.

It's roughly equivalent to

(export STUFF=Blah; env | grep STUFF)

in that the assignment to STUFF does not affect the current shell, only env. (I say "roughly", because in this example STUFF is in the environment of every command executed in the subshell, not just env.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.