QuickPrototype
QuickPrototype

Reputation: 883

BASH Variable scope in subscript

I have a script Onstartup.sh which loops through 3 scripts:

#!/bin/bash

#Check services are up and running every 30seconds
while true; do
    . ./script1.sh &
    ./script2.sh &
    ./script3.sh &
    sleep 30
done

script1.sh is giving me the problem where a variable is loosing its value.

#!/bin/bash

echo -e "Variable _X:($_X)"

if [[ $_X -ne 1 ]]; then
    if [ $(somefunction) -ge 1 ]; then
            echo "fix stuff"
        else 
            export _X=1
            echo -e "Variable post script:($_X)"
        fi
    fi
else
    echo "dont fix stuff"
fi

script1.sh runs and fixes stuff then to make it not run again I set _X=1 however the next time the loop runs _X is blank again?

I use the . (dot) script as this means run in current shell so the _X value should be retained?

Upvotes: 0

Views: 2535

Answers (1)

Barmar
Barmar

Reputation: 780818

Don't run script1.sh in the background, because that runs it in a subprocess, so its variable assignments don't have any effect on the original shell.

while true; do
    . ./script1.sh
    ./script2.sh &
    ./script3.sh &
    sleep 30
done

Upvotes: 2

Related Questions