passing env variables to commands in bash

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="foo"
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).

Tags:

Bash