6

I am trying to check if a MYSQL user exists. This is as far as I have got. I fall down on capturing the answer from the output.

 #!/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 output I am getting

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

Can any one help please

2 Answers 2

11

Thanks very much for your help. Here is the final result working.

It needs the -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
Sign up to request clarification or add additional context in comments.

1 Comment

rather obvious, but just to be affirmative... this worked for me with shell_exec --> $is_mysql_user = shell_exec('mysql --defaults-extra-file=MYPATHTOSTOREDCREDENTIALS -sse "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = \'' . $user_name . '\')"');
3

Assigning the result to a variable can be done like this:

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

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

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

1 Comment

Thanks very much. I am then trying to pick up the result. This gives me an error if [ $RESULT_VARIABLE = "1" ]; then echo "true" else echo "try again" fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.