abhisek
abhisek

Reputation: 27

passing variable from one script to another in shell scripting

I have a script suppose script.sh it has two scripts to run parallaly inside

sh script1.sh &
sh script2.sh &
wait;
echo $var1
echo $var2

i want to get these two variable(var1,var2) printed while running script.sh

cat script1.sh

var1=1;
export $var1

cat script2.sh

var1=1;
export $var1

Upvotes: 0

Views: 659

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295403

This can be done with coprocesses in bash 4.x, if your script1 and script2 write their variables to stdout:

#!/usr/bin/env bash
#              ^^^- Must be bash, not /bin/sh; must NOT start this script with "sh name".

start_seconds=$SECONDS
run_script1() { sleep 5; echo "one"; }  # replace these with your script1 or script2
run_script2() { sleep 5; echo "two"; }

coproc coproc_script1 { run_script1; }
coproc coproc_script2 { run_script2; }

read -u "${coproc_script1[0]}" var1
read -u "${coproc_script2[0]}" var2
echo "End time: $(( SECONDS - start_seconds )); var1=$var1; var2=$var2"

If the values weren't running in parallel, your End time would be 10 or more. Instead, it should in practice be 5 or 6 with the above code.

Upvotes: 1

mpasko256
mpasko256

Reputation: 841

Things that come to mind:

  1. If you use bash, you can run a script using dot:

    .script1.sh

    It will run script in the same environment, so you can modify environment variables of the "invoker" script.

  2. If it is a single output data, you can just print into a standard output of the inner script and intercept in the outer script:

    inner_result=`script1.sh`

  3. If it is a numeric value, you can return it as a exit code of the script (but I do not recommend this method as it is a bad practice in script development)

Edit:

  1. Use temporary file to store result and then remove it (but depending on operating system, named queues could be best dedicated solution)

Upvotes: 0

Related Questions