0

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?

3
  • 3
    Running the script in the background runs it in a subshell, so variable assignments do not affect the original shell. Commented Jun 30, 2015 at 21:55
  • Try X=1 & followed by echo $X and you'll see that the assignment has no effect. Commented Jun 30, 2015 at 21:56
  • Thanks! 100% scripts in background are new processes. Commented Jul 1, 2015 at 8:16

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

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.