Trying to check if Mysql user exists in bash script

I am trying to check if a MYSQL user exists. That's all I have. I fall for receiving a response from the exit.

 #!/bin/bash
echo -e "What is the MYSQL username called"
    read DBUSER
    if [ -z "$DBUSER" ]
    then
    exit

    mysql -uUSER -pPASS -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$DBUSER')";

    if 
    yes
    do this
    else
    do this

this is the result that I get

+-----------------------------------------------------+
| EXISTS(SELECT 1 FROM mysql.user WHERE user = 'bob') |
+-----------------------------------------------------+
|                                                   1 |
+-----------------------------------------------------+

Can anyone please help

+4
source share
2 answers

Many thanks for your help. Here is the final result of the work.

He needs -sse

RESULT_VARIABLE="$(mysql -uUSER -pPASS -sse "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$DBUSER')")"

if [ "$RESULT_VARIABLE" = 1 ]; then
echo "TRUE"
else
  echo "FALSE"
fi
+5
source

Assigning the result to a variable can be done as follows:

RESULT_VARIABLE="$(mysql -uUSER -pPASS -se "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$DBUSER')")"

And you can also use a column alias in MySQL, btw.

SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = '$DBUSER') AS does_it_exist
+3
source

All Articles