In a given shell, normally I\'d set a variable or variables and then run a command. Recently I learned about the concept of prepending a variable definition to a command:
Use env
.
For example, env FOO=BAR command
. Note that the environment variables will be restored/unchanged again when command
finishes executing.
Just be careful about about shell substitution happening, i.e. if you want to reference $FOO
explicitly on the same command line, you may need to escape it so that your shell interpreter doesn't perform the substitution before it runs env
.
$ export FOO=BAR
$ env FOO=FUBAR bash -c 'echo $FOO'
FUBAR
$ echo $FOO
BAR
How about exporting the variable, but only inside the subshell?:
(export FOO=bar && somecommand someargs | somecommand2)
Keith has a point, to unconditionally execute the commands, do this:
(export FOO=bar; somecommand someargs | somecommand2)
A simple approach is to make use of
;
For example:
ENV=prod; ansible-playbook -i inventories/$ENV --extra-vars "env=$ENV" deauthorize_users.yml --check
FOO=bar bash -c 'somecommand someargs | somecommand2'
Use a shell script:
#!/bin/bash
# myscript
FOO=bar
somecommand someargs | somecommand2
> ./myscript
You can also use eval
:
FOO=bar eval 'somecommand someargs | somecommand2'
Since this answer with eval
doesn't seem to please everyone, let me clarify something: when used as written, with the single quotes, it is perfectly safe. It is good as it will not launch an external process (like the accepted answer) nor will it execute the commands in an extra subshell (like the other answer).
As we get a few regular views, it's probably good to give an alternative to eval
that will please everyone, and has all the benefits (and perhaps even more!) of this quick eval
“trick”. Just use a function! Define a function with all your commands:
mypipe() {
somecommand someargs | somecommand2
}
and execute it with your environment variables like this:
FOO=bar mypipe