0

If I source the same shell script from multiple other scripts, which I run in parallel, and modify a shell variable defined in the sourced script, will the sourcing scripts mess up each other's value of that variable?

Example :

  • source.sh
    #!/bin/bash
    
    some_value=$1+10
    
  • file-1.sh
    #!/bin/bash
    
    source ./source.sh 5
    ./some-script $some_value
    
  • file-2.sh
    #!/bin/bash
    
    source ./source.sh 10
    ./some-script.sh $some_value
    

2 Answers 2

2

You have as many environment or shell variables $some_value as you have processes which define them.

Then if you launch at the same time file-1.sh and file-2.sh you will have different values since you have different processes. Note that source doesn’t create process, the sourced script works with the file-1.sh and with the file-2.sh process environments.

1

When you source a shell-script, that means the current shell instance is reading the script line-by-line and executing the commands on the spot, as if you had entered them on the command-line (if you are executing the source call from the prompt) or as if you had copy-and-pasted them into the script (if you are sourcing from a script).

Therefore, the different shell scripts file-1.sh and file-2.sh both behave as having a locally defined shell variable that only coincidentally has the same name some_value in both cases. Even if you ran the two scripts in parallel, they would not know anything about each other, and so there are no cross-interactions between them - the sub-shell in which file-1.sh is running does not know that the sub-shell in which file-2.sh is running also happens to have a variable some_value defined.


As a side note, your attempt at creating an arithmetic expression as

some_value=$1+10

will not have the effect you may imagine. For file-1.sh it will yield 5+10 literally, and for file-2.sh it will yield 10+10 literally. In order to perform arithmetic evaluation, you have to place it in an arithmetic expansion, as in

some_value=$(($1+10))

I would recommend checking shell-scripts with shellcheck, also available as standalone tool on many Linux distributions, to catch syntax (and some logical) errors.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .