The command
file="test" echo $file
doesn't output test
because the expansion occurs before running the command. Check this out:
$ set -x
$ foo='hello' echo $foo
+ foo=hello
+ echo
The same thing doesn't occur when you run a Unix shell script instead of running a shell command, e.g.,
foo='hello' /path/to/script.sh
In this case, the foo='hello'
assignment is first resolved, then /path/to/script.sh
is run.
Some previous and related posts proposed solutions for persistent variable assignment + CLI commands:
foo='hello' bash -c 'echo $foo'
: Using shell script is not desirable! Wordy approach to simple commands.
(){ local var=value; echo "1: $var"; }; echo "2: $var"
: Using functions is not desirable! Wordy approach to simple commands.
TEST=foo && echo $TEST
: Simple but persistent.
My way out is
(file="test"; echo $file)
By creating a subshell, you can create a shell variable, use it in the echo
command, and then it won't persist outside this command.
file
is set only forecho
, but$file
is expanded beforeecho
runs (it has to be) so$file
is empty when it’s expanded. Try the example given in the linked answer, using a shell script: you’ll see that the variable is indeed set for the command (in a non-persistent manner).file="test" echo $file
does exactly what you want it to do. Can you edit and clarify the use case? Do you really want the variable to only be available in the command's environment, or do you want it to be available in the parent (which is whatecho "$var"
requires) but to then be unset after the command finishes? If you only want it to exist in the command's environment, "for the lifetime of the command" thenvar=foo command
is the right way.