Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass argument to a subshell (by execute, NOT source) without command line argument?

For example, I have a main shell program main.sh, and I have another subshell program sub.sh. I want to pass a variable var to the subshell, but I do not want to use command-line argument. An example code is the following:

#In main.sh
a=1
./sub.sh

#In sub.sh
echo $a

I want to see the output: 1

I know this question is weird, but this feature best suits my need. I can't source the sub.sh because in the actual program I have a LOT of variables to pass in... Thanks!

EDIT: What if I run sub.sh in the backgroun and it takes 10 hours, and I want to run another sub.sh in the foreground for another variable b?

like image 736
return 0 Avatar asked Dec 03 '25 14:12

return 0


1 Answers

You just have an extra newline:

#In main.sh
a=1 ./sub.sh

This is really the same answer as 1_CR, but demonstrates the technique of passing a value to the environment of sub.sh instead of modifying the current environment for sub.sh to inherit.

Since this is a per-process modification of the environment, you can repeat as necessary.

a=1 ./sub.sh &
a=3 b=9 ./sub.sh &

Each instance of sub.sh sees a different value for a, and the second instance sees a value for b as well.

like image 100
chepner Avatar answered Dec 07 '25 05:12

chepner



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!