This question already has an answer here:

I have this sample bash command:

FILE='/tmp/1.txt' echo "file: $FILE"

and the output is:


Why the output doesn't contain defined earlier variable FILE?

marked as duplicate by Stephen Kitt, Kusalananda, Jeff Schaller, thrig, Sundeep Feb 16 '17 at 15:00

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


When you run

FILE='/tmp/1.txt' echo "file: $FILE"

The shell expands the $FILE variable before performing the assignment, so assuming FILE was unset previously, you'd get:

FILE='/tmp/1.txt' echo "file: "

You can confirm this behavior by setting FILE to a known value first:

FILE='/tmp/1.txt' echo "file: $FILE"

The second line is expanded to:

FILE='/tmp/1.txt' echo "file: foo"

Then the value of FILE, in the context of this command, is changed to /tmp/1.txt. Then the shell executes echo "file: foo"

As @admstg mentioned in his response, you can do:

FILE='/tmp/1.txt'; echo "file: $FILE"

But that behavior is different than what you were originally trying. What you had initially sets FILE only for the duration of the echo command; the above sets it for the duration of the shell (or until it is explicitly unset).


You should separate the two commands by ; in order to define the variable then by calling it.

As you are calling the variable in the same shell you don't need to export the variable.

This should work :

FILE='/tmp/TEST.txt' ;  echo "file : $FILE"

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