Sunday, July 9, 2017

Bash - exit on failure

The problem

Scripts like the following will execute each step, even if one fails:

 #!/bin/bash
 
 echo "Shutting down mysqld. Please wait."
 
 # following shuts down mysql before stopping the container
 docker exec mysql /usr/bin/mysqladmin shutdown
 
 echo "Stopping the individual containers..."
 
 # stop the containers
 docker stop mysql
 docker stop sphinx
 docker stop apache

The problem with the above is that: if MySQL service does not completely shutdown (i.e., has some sort of error), there is nothing to stop the script from executing the last three steps. Without the database services stop, those will corrupt your database. (I learned this the hard way.)

One solution

The desirable solution is for the script to exit without stopping the Docker services. This can be done by making the MySQL shutdown line look like:

 docker exec mysql /usr/bin/mysqladmin shutdown || \
  { echo 'MySQL shutdown failed' ; exit 1; }

Note: above should all be on a single line (without the "\").

The above gives you a warning that something didn't work right and exits the script before attempting to stop the Docker containers.

No comments:

Post a Comment