If I run
export TEST=foo echo $TEST
It outputs foo.
If I run
TEST=foo echo $TEST
It does not. How can I get this functionality without using export or a script?
This is because the shell expands the variable in the command line before it actually runs the command and at that time the variable doesn't exist. If you use
it will work.
I suspect you want to have shell variables to have a limited scope, rather than environment variables. Environment variables are a list of strings passed to commands when they are executed.
You're passing the
If you had written
That would have been another matter. Here, we're passing
Now, if as I suspect, what you want is to limit the scope of shell variables, there are several possible approaches.
Portably (Bourne and POSIX):
The (...) above starts a sub-shell (a new shell process), so any variable declared there will only affect that sub-shell, so I'd expect the code above to output "1: value" and "2: " or "2: whatever-var-was-set-to-before".
Linuxly (specified by the LSB and Debian policy, so supported by the
With zsh, you can use inline functions:
With bash and zsh (but not ash, pdksh or AT&T ksh), this trick also works: