2 Replies Latest reply: Oct 6, 2013 4:54 AM by Tommyreynolds-Oracle RSS

    Scope issue: Trying to set the value of a variable in a calling (upper) script from a called (lower) script

    966239

      Hi,

       

      I have a basic scope question . I have two .ksh scripts. One calls the other.

       

      I have a variable I define in script_one.ksh called var1.

       

      I set it equal to 1. so export var1=1

       

      I then call script_two,ksh from script_one.ksh.  In script_two.ksh I set the value of var1 to 2 . so var1=2.

       

      I return to script_one.ksh and echo out var1 and it still is equal to 1.

       

      How can I change the value of var1 in script_two.ksh to 2 and have that change reflected in script_one.ksh when I echo var1 out after returning from script_two.ksh.

       

      I've remember seeing this I just can't remember how to do it.

       

      Thanks in advance.

        • 1. Re: Scope issue: Trying to set the value of a variable in a calling (upper) script from a called (lower) script
          Catch-22

          Unfortunately Unix or Linux does not have a concept of dynamic system kernel or global variables.

          Environment variables can be exported from a parent to a child processes, similar to copying, but a child process cannot change the shell environment of its parent process.

           

          However, there are a few ways you could use: You can source execute the scripts, using the Bash source command or by typing . space filename. When source executing a script, the content of the script are run in the current shell, similar to typing the commands at the command prompt.

           

          Use shell functions instead of forking shell scripts.

           

          Store the output of a script into a variable. For instance:

           

          #test1.sh

          var=goodbye

          echo $var

           

          #test2.sh

          var=hello

          echo $var

          var=`./test1.sh`

          echo $var

           

          $ ./test2.sh

          hello

          goodbye

          • 2. Re: Scope issue: Trying to set the value of a variable in a calling (upper) script from a called (lower) script
            Tommyreynolds-Oracle

            It all depends on how much data you need to return.  If it is only one variable, you can do this:

             

            Script 1:

             

                #!/bin/sh

               i=0 export I

               while true; do

                  i=`script two`

               done

             

            Script 2:

             

                #!/bin/sh

                echo "i=$i" >&2

                echo `eval $i + 1`

             

            In other words, you can export the variables in script #1 and then parse the output of script #2.  Since script #2 is a child of script #1, script #2 inherits the exported shell variables from script #1.