简体   繁体   English

Linux bash脚本表现得很奇怪

[英]Linux bash script acting weird

I have a simple bash script that is suppose to monitor if mysql is up or down. 我有一个简单的bash脚本,可以监视mysql是up还是down。 If it is down, i want to also stop HAProxy from running. 如果它关闭,我想也阻止HAProxy运行。 Below is my simple bash script: 下面是我简单的bash脚本:

#!/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. MySQL运行或不运行部分工作正常。 It is the stopping HAProxy part that seems to have an issue. 停止HAProxy部分似乎有问题。 What is happening is that HAProxy stops when mysql stops. 发生的事情是当mysql停止时HAProxy停止。 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. 但是当我启动MySQL和HAProxy时,即使MySQL启动并运行,脚本似乎也会继续停止HAProxy。

In your script, you are unconditionally executing sudo service haproxy stop and storing the output in $msg using command substitution. 在您的脚本中,您无条件地执行sudo service haproxy stop并使用命令替换将输出存储在$msg

You could store the command in a variable, but this is considered very bad practice (see Bash FAQ 050 ). 您可以将命令存储在变量中,但这被认为是非常糟糕的做法(请参阅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): 相反,尝试将命令分配给函数并稍后调用它( function关键字是可选的和Bash特定的,为了便于携带而留下它):

#!/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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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