Please consider this code:

    mysql -u root -p << MYSQL
        drop user '${test}'@'localhost';
        drop database ${test};

        create user '${test}'@'localhost' identified by '${psw}';
        create database ${test};
        GRANT ALL PRIVILEGES ON ${test}.* TO ${test}@localhost;

The code outputs the following error for the first command drop user '${test}'@'localhost';:

ERROR 1396 (HY000): Operation DROP USER failed for '${test}'@'localhost'

My question

How could I make the program ignores this error if it appears, so that execution doesn't break?

For example, how could I make sure the program will behavior this way:

"Drop if you already have a user by the value of ${test}, and if you don't, just continue to create it".

Of course, the same question goes for the second drop command dealing with the DB instance.


Use IF EXISTS clause:

DROP USER IF EXISTS '${test}'@'localhost';

An error occurs if you try to drop an account that does not exist. If the IF EXISTS clause is given, the statement produces a warning for each named user that does not exist, rather than an error.



You could also force the mysql tool to ignore errors on all commands:

If you want the script to continue even if some of the statements in it produce errors, you should use the --force command-line option.

i.e. mysql --force -u root -p << ...

  • 1
    @Arcticooling, no, sorry, I was too brief, edited. – ilkkachu Dec 2 '17 at 23:04
  • Hmm, I assume it will runover/runthrough the sexisting once already created with the same name (in case I created them manually before executing my above code). – Arcticooling Dec 2 '17 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.