1

I have a the function is_mysql_db() to identify if the installed database in the server is a mysql server. So ideally the code in main body should call the function to determine whether I should consider this server a mysql server or not.

I tried at the end of the function to put double brackets, single "=", using or not variable for comparison. I am honestly out of ideas and I would like this code to look as clear as possible as this is only a small part of it.

Below my sample code:

#!/bin/bash

is_mysql_db(){
    yum_mysql_out=$(yum list installed | grep mysql-community | awk '{ print $1 }' | tail -n1)
    [ $yum_mysql_out == "mysql-community-server.x86_64" ]
}


if [ is_mysql_db ]
then
        echo "Installed"
else
        echo "Not Installed"
fi

I would expect if the MySQL yum package is installed to detect it and return the package is installed and if its not to return Not Installed. Simple but not that much apparently.

Gaita
  • 15
  • 3
  • You need to remove the brackets in the if. `if command; then ...` will execute the `then` block if the command exits with 0. `[...]` is useful when you need to use operators such as the `=`/`==` you use in the function. – Aaron May 27 '19 at 14:33
  • And it looks like you could simplify the whole thing as `if yum list installed | grep "mysql-community-server.x86_64"; then echo Installed; else echo "Not Installed"; fi` – Aaron May 27 '19 at 14:35

1 Answers1

2

It's not the shell function that is wrong, it's your call to it.

Putting a string inside square brackets does not run that command, it just tests that the string itself is non-empty.

Don't put the function in the square brackets, and it will run it as a command.

Example:

$ if [ false ] ; then echo "false is true??"; else echo "false is false as expected" ; fi

false is true??

$ if false ; then echo "false is true??"; else echo "false is false as expected" ; fi

false is false as expected

By the way, your function could be simpler:

is_mysql_db(){
    yum list installed | grep -q mysql-community-server
}

Or even use rpm directly, so yum doesn't re-load its package indexes:

is_mysql_db(){
    rpm --quiet -q mysql-community-server
}
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828