User Tools

Site Tools


I have used *nix Bourne Again Shell (BASH) scripts occasionally in the past. Although I know what they are and how to use them, I have never actually written one myself before.

Today, I had a plan to backup all the MySQL databases on this server and writing a BASH script to help me do that easily seemed like a very good idea. I started searching the WWW for BASH shell scripting tutorials bright and early this morning, and within a couple of hours, I had written a script that did the job!

In other words, BASH only seemed difficult and complicated (to me) but it's really not…

I will paste my script below. It's not perfect and I know there is a lot of room for improvement but considering that I started learning BASH shell scripting this morning, I am quite pleased with it.

A BASH script to backup MySQL databases.

I only use a total of 4 MySQL databases on this server and I have root access to the MySQL server, which makes it very easy for me to use this script.

echo -n "Please enter the database name [* for all]: "
read db_name
if [ ! -n "$db_name" ]
        echo "Invalid Input. Exiting..."
        exit 1
if [ "$db_name" = '*' ]
        db_name="--databases network_db1 network_db2 network_db3 network_db4"
if [ -e $file_name ]
        rm -f $file_name;
# mysqldump
echo -e "SET FOREIGN_KEY_CHECKS=0;\n" | bzip2 > $file_name
mysqldump -cC --opt --skip-lock-tables --single-transaction -u root -p $db_name | bzip2 >> $file_name
echo "SET FOREIGN_KEY_CHECKS=1;" | bzip2 >> $file_name
exit 0

Even now, as I write this and review the code, I see a few lines I could change and I probably will, first thing tomorrow morning.

I will also write about the things I had to figure out the hard way, but that's for tomorrow as well.

handbook/handbook/bash4.txt · Last modified: 2010/04/15 21:18 (external edit)