Is there a way to pass an environment variable to two processes that are started in one line in bash? I want to execute two processes in the same command line
# these are ways to execute two processes in the same line
exec1 & exec2
exec1 && exec2
exec1 || exec2
exec1; exec2
And this is the way to pass an environment variable to a process:
VAR=value exec
How can I combine both?
# this is not enough because exec2 does not see VAR
VAR=value exec1 & exec2
I know the way to do it with export:
export VAR=value; exec1 & exec2; unset EXPORT
Is there another way to do it without export?
Yes, you can do this: Scope the export to a subshell. (If you then exec one of the processes from the subshell, you're not taking an efficiency loss in the branch where that line is reached since the fork used to spawn the subshell is the same one that would otherwise be going to run the subprocess). Thus:
(export VAR=value; exec1 & exec exec2)
(export VAR=value; exec1 && exec exec2)
(export VAR=value; exec1 || exec exec2)
(export VAR=value; exec1; exec exec2)
Obviously this is going to have undesired side effects if either of your commands were not actually external but were a shell builtin.
However, my advice? Don't. This makes your code less readable for very, very little gain. Repeating yourself isn't the end of the world in this case.
This may get messy with quoting hell: group the commands to call in a subshell
VAR=value sh -c 'exec1 & exec2'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With