3

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?

return 0
  • 4,226
  • 6
  • 47
  • 72

2 Answers2

3

You could just export the variable a

a=1
export a
./sub.sh

This causes a to be in the environment of subsequently executed commands

iruvar
  • 22,736
  • 7
  • 53
  • 82
  • 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? – return 0 Oct 25 '13 at 21:09
  • @return0, It sounds like you probably need chepner's solution – iruvar Oct 25 '13 at 21:10
3

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.

chepner
  • 497,756
  • 71
  • 530
  • 681