Home > Software design >  Does bash use dynamic or static scope when calling a script within another script
Does bash use dynamic or static scope when calling a script within another script

Time:11-12

If you have a script: test1.sh

var="first"
echo $var

and test2.sh

var="second"
sh ./test1.sh
echo $var

what is the expected output of executing test2.sh if bash uses dynamic scoping and if it uses static scoping?

From my understanding, bash uses dynamic scoping, so I was expecting that when test2.sh is run, $var gets set to "second" and when test1.sh is run from within test2.sh, var gets set to "first". Thus expected output would be: first first

However, I get the output: first second

which suggests to me that this is static scope? Unless my understanding is wrong here

CodePudding user response:

Does bash use dynamic or static scope when calling a script within another script

There is no "dynamic" nor "static" scope in shell. In Bash, there is only function "scope", but it is not relevant here.

There are processes. Processes are separate entities, with separate memory space. Just like firefox can't change chrome, the child process can't change the parent process.

what is the expected output of

The output is first second. sh runs a new process, named sh. The child process can't affect parent process variables.

Note that a child process started with a command inherits only exported variables. If var is not exported, it is unset on the start of test1.sh.

  • Related