2

How to determine if there is a user in mysql in BASH ?

if [ "$NAME_USER" == ???? ]; then
  echo "User exists in MySQL"
else
  echo "User no exists in MySQL"
fi
0

2 Answers 2

4
while read User; do
    if [[ "$NAME_USER" == "$User" ]]; then
        echo "$User exists in MySQL"
        break
    fi
done < <(mysql -B -N -e 'use mysql; SELECT `user` FROM `user`;')

if [[ "$NAME_USER" != "$User" ]]; then
    echo "$NAME_USER does not exists in MySQL"
fi
Sign up to request clarification or add additional context in comments.

4 Comments

Using backticks in double quotes will cause the shell to execute "user". Also, you probably want -B and -N for mysql so the table header is not included in the output.
@jordanm thanks for correcting me on the quotes. I'm not using mysql very often in scripts, but when I do (usually I pipe the output to further process) table headers are excluded...
That probably depends on client version. From my experience, when used in a pipeline, it implies -B, but not -N.
I had to use xargs to strip the carriage return at the end of each value in $User for this to work.
0

You can enclose a script to make a mysql query and then parse the output.

Comments

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.