Reputation: 1075
I have a simple bash script that is suppose to monitor if mysql is up or down. If it is down, i want to also stop HAProxy from running. Below is my simple bash script:
#!/bin/bash
nc -z 127.0.0.1 3306
rt_val=$?
msg=$(sudo service haproxy stop);
if [ $rt_val != 0 ]; then
eval $msg
exit 3
else
exit 0
fi
The MySQL running or not part is working just fine. It is the stopping HAProxy part that seems to have an issue. What is happening is that HAProxy stops when mysql stops. But when i fire up MySQL and also HAProxy, it seems like the script continues to stop HAProxy even if MySQL is up and running.
Upvotes: 2
Views: 248
Reputation: 4681
In your script, you are unconditionally executing sudo service haproxy stop
and storing the output in $msg
using command substitution.
You could store the command in a variable, but this is considered very bad practice (see Bash FAQ 050). Instead, try assigning the command to a function and calling it later (the function
keyword is both optional and Bash-specific, leave it out for portability):
#!/bin/bash
function stopcmd() { sudo service haproxy stop ; } # semicolon needed if on single line
nc -z 127.0.0.1 3306
rt_val=$?
if [ $rt_val != 0 ]; then
stopcmd
exit 3
else
exit 0
fi
Furthermore, neither the function nor the test ([ ... ]
) is really necessary in this simple case. Your script can be written as:
#!/bin/bash
if nc -z 127.0.0.1 3306
then
exit 0
else
sudo service haproxy stop
exit 3
fi
Upvotes: 7