How do i use bash variables between shell scripts?



  • Using bash variables between shell scripts is the area of Variable Scope, this is similar to other programming languages. Variable scope determines where in the scripts a defined variable can be used.

    To demonstrate this, with two scripts, one script calls another script. The second script tries to use a variable from the first script. Let's see the results of this.

    First script. that calls the second script.

    #!/bin/bash
    Myvar=pineapple
    echo "My favourite fruit is $Myvar"
    ./mysecond.sh
    

    Second script That tries to use the variable $Myvar

    #!/bin/bash
    echo "But Barney does not like $Myvar"
    

    Run the first script.

    $ ./myfirst.sh 
    My favourite fruit is pineapple
    But Barney does not like 
    

    The result is: the second script runs but does not know what the $Myvar variable is, so does not print it.

    In order to have the second script know about the $Myvar the scope can be extended to the second script by using the export command.

    Edit the first script to run the export command.

    #!/bin/bash
    Myvar=pineapple
    export Myvar
    echo "My favourite fruit is $Myvar"
    ./mysecond.sh
    

    Run the first script again.

    $ ./myfirst.sh 
    My favourite fruit is pineapple
    But Barney does not like pineapple
    

    Now the second script knows what the $Myvar is set to.


Log in to reply
 

© Lightnetics 2024