user3441151 user3441151 - 3 months ago 8
Bash Question

bash script not giving the MariaDB service status correctly

I have to check my MariaDB Service is running or not in CentOS 7.

For this I just create the .sh file. Content of this file is below

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


when I run the following command

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


If service is running return 1

If service is stop return 0

above output is correct.

But when I
execute my .sh file
it gives the wrong output

If service is running return (mariadb is not running!!!)

If service is stop return (mariadb is not running!!!)

Answer

( is for creating a subshell, and is probably not really what you want here. You could do

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

but really this would be much easier with pgrep instead of building your own pipeline to find the process. Try:

#!/bin/bash
service=mariadb

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

pgrep will exit with 0, which is success when it's an exit status, if it finds something, or 1 if it does not find any matching processes.

Also, I switched to printf instead of echo. It shouldn't be a problem with this example, but echo isn't the preferred way most of the time

In your attempt with the parenthesis, you're trying to use > as a greater-than comparison, but it will actually be consumed by the shell as a redirection operator (I bet you have a file called 0 in that directory now). If you want to do arithmetic stuff you need double parens ((...)) or, if you want to test things you can use the square brackets as I did above. The single parenthesis means to run the contained commands in a subshell though.

Comments