bash 脚本没有正确给出 MariaDB 服务状态

标签 bash shell centos mariadb centos7

我必须检查我的 MariaDB 服务是否在 CentOS 7 中运行。

为此,我只创建了 .sh 文件。该文件的内容如下

#!/bin/bash
service=mariadb

if ( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 )
then
  echo "$service is running!!!"
else
  echo "$service is not running!!!"
fi

当我运行以下命令时

ps -ef | grep -v grep | grep mariadb | wc -l

如果服务正在运行返回1

如果服务停止返回0

以上输出是正确的。

但是当我执行我的 .sh 文件时,它给出了错误的输出

如果服务正在运行返回(mariadb 没有运行!!!)

如果服务停止返回(mariadb 没有运行!!!)

最佳答案

( 用于创建子 shell,可能并不是您真正想要的。您可以这样做

if [ $(ps -ef | grep -v grep | grep "$service" | wc -l) -gt 0 ]; then

但实际上,使用 pgrep 比构建自己的管道来查找进程要容易得多。尝试:

#!/bin/bash
service=mariadb

if pgrep -f "$service"
then
    printf '%s is running!!!' "$service"
else
    printf '%s is not running!!!' "$service"
fi

pgrep 将以 0 退出,如果它是退出状态,则成功,如果它找到什么,或者 1 如果没有找到任何匹配的进程。

此外,我切换到 printf 而不是 echo。这个例子应该没​​有问题,但是 echo isn't the preferred way most of the time

在你尝试使用括号时,你试图使用 > 作为大于比较,但它实际上会被 shell 作为重定向运算符使用(我敢打赌你有一个现在该目录中名为 0 的文件)。如果你想做算术运算,你需要双括号 ((...)) 或者,如果你想测试一些东西,你可以像我上面那样使用方括号。单括号表示在子 shell 中运行包含的命令。

关于bash 脚本没有正确给出 MariaDB 服务状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38813506/

相关文章:

php - 关于如何在 linux 中与另一个 shell 交互使用 shell 的一些问题

bash - "key=value bash-script"用法记录在哪里?

linux - 运行 shell 脚本一段时间

bash - 在第一行之后停止读取行循环时的Shell脚本

mysql - Centos 7 上 MySQL 服务器的身份验证问题

centos - 在 centos 7 中安装 Ganglia 失败(rrd create in -rrd ... no)

node.js - 端口打开但连接被拒绝...centos 8/nginx/react/nodejs

bash echo 执行命令而不是打印它

bash - 是否可以在 bash 语法中使用变量?

linux - Expect脚本完成后不退出