Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass the same environment variable to two processes in one line

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?

like image 447
4 revs, 2 users 76% Avatar asked Dec 11 '25 22:12

4 revs, 2 users 76%


2 Answers

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.

like image 172
Charles Duffy Avatar answered Dec 13 '25 16:12

Charles Duffy


This may get messy with quoting hell: group the commands to call in a subshell

VAR=value sh -c 'exec1 & exec2'
like image 45
glenn jackman Avatar answered Dec 13 '25 17:12

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!