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). – Stephen Kitt Feb 02 '24 at 16:18file
?". "Try the example given in the linked answer, using a shell script", my idea is to not resort to shell scripts. I have a answer for my own question (none of the aforementioned Q&A answered it). Open it so that I can answer it. – Rubem Pacelli Feb 02 '24 at 16:24file="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. – terdon Feb 02 '24 at 16:57echo
doesn't care about any variables in the environment, (except when they are embedded in the cmd line arguments or as otherwise evaluated by the cmd-processing loop). But take the case of a program that has its own env var,less
, If you have an env varexport LESS=-CQaix4
, you can override that (just the one time) withLESS= less /path/to/some/file
. When you open the file all of the features from-CQaix4
are gone.less
is always looking in its environment for$LESS
. (just for example). – shellter Feb 03 '24 at 04:40(var=value; echo "1: $var"); echo "2: $var"
The (...) above starts a sub-shell". – muru Feb 04 '24 at 13:11