简体   繁体   中英

Linux bash script acting weird

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM