Passing one shell script variable to another shell script

16,056

Solution 1

Assigning a variable is a command. Unless you're prepared to write a bash parser in bash, what you want cannot be done.

Solution 2

If your variable assignments are only ever in the exact form indicated above, that is

export a=10

then you could extract those assignments with grep and eval the results. Your script2.sh would then be

eval `grep "^export " script1.sh`
echo $a

But doing this is very fragile, and can break in lots of ways. Putting the variable assignments in a third script sourced by both as others have suggested is far safer.

This can break if you have variable settings inside conditionals, or if your exported variables depend on other non-exported variables that got missed, or if you set and export the variables separately; and if you happen to be using command substitution in your exports those would still get run with their possible side effects.

if [ $doexport = 1 ]; then
  export a=1
fi

a=2
export a

b=2
export a=$b

export a=`ls |wc -l`

These are all potentially problematic.

Solution 3

What you are trying to do (only get the variables from another script, without executing the commands) is not possible.

Here is a workaround:

Extract the variable declaration and initialisation to a third file, which is then sourced by both.

common-vars:

export a=10
export b=20

script1.sh:

. common-vars
echo "testing"
exit

script2.sh:

. common-vars
echo $a
Share:
16,056
Karthik
Author by

Karthik

Updated on July 26, 2022

Comments

  • Karthik
    Karthik almost 2 years

    I am trying to access one script variable from another script for example,

    script1.sh:

    export a=10
    export b=20
    echo "testing"
    exit
    

    script2.sh:

    . script1.sh
    echo $a
    

    The problem involved here is its able to access the variable 'a' from the script1 in script2 but its executing all the commands written in script1.sh which is annoying. I just want to access only the exported variables in script1 and donot want to run the commands in script1 while calling that in script2.

    Kindly help!

    Thanks,
    Karthik

  • Karthik
    Karthik almost 13 years
    Both answers suggested by you and jlliagre really works but can you explain the limitation of using this approach in detail?