Alex
Alex

Reputation: 1486

Shell Script Variable Scope

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)

Upvotes: 2

Views: 863

Answers (1)

Timur Shtatland
Timur Shtatland

Reputation: 12540

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

Upvotes: 3

Related Questions