2

We have two shell scripts (A & B) running parallelly on the same Linux machine. Here is the code of script A

#!/bin/bash
MY_VAR=Hello
// Script Code run for 5-10 seconds

Here is script B

#!/bin/bash
MY_VAR=HI
// Script Code run for 5-10 seconds

What will be the scope for the MY_VAR variable, If both scripts are running parallelly?

For example, if we start script A, and while script A is running we start script B. Would change in MY_VAR value in script B change it for script A as well (wherever we are accessing it in script A)

1
  • 1
    Fortunately, a bash variable is bound to one process. Several bash processes have their own set of variables. Imagine the havoc you could do, if shells would share their variable? You could ruin any shell script, which is running at the moment, by fiddling around with the variables it uses. Commented Oct 19, 2020 at 9:24

1 Answer 1

3

The scope of each variable is only within its corresponding script. In the case you described there is no leakage outside of the script. There is no interference between the scripts. Even if you EXPORT the variable, there is no effect.

Example:

==> test1.sh <==
#!/usr/bin/env bash

echo "${MY_VAR} in 1"
export MY_VAR=Hello

for i in `seq 1 10` ; do
    echo "${MY_VAR} in 1"
    sleep 5
done

==> test2.sh <==
#!/usr/bin/env bash

echo "${MY_VAR} in 2"
export MY_VAR=Hi

for i in `seq 1 10` ; do
    echo "${MY_VAR} in 2"
    sleep 5
done

Run the scripts:

./test1.sh & ; sleep 10; ./test2.sh &
 in 1
Hello in 1
Hello in 1
 in 2
Hi in 2
Hello in 1
Hi in 2
Hello in 1
Hi in 2
Hello in 1
Hi in 2
Hello in 1
Hi in 2
Sign up to request clarification or add additional context in comments.

1 Comment

By leakage I mean a case when variable defined in one scope affects the variable with the same name in another scope. In the case you described, the variable in script A does not affect the variable with the same name in script B.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.