0Neji 0Neji - 7 months ago 15
Bash Question

Catching mysqldump error in bash script

I'm currently trying to write a script that backs up several of my sites along with their databases.

All is working well but I'm trying to be a little cleverer with my log - basically, at the moment it will attempt to run mysqldump and will echo success or failure.

What I'd rather do is output the actual error rather than just an unhelpful 'mysqldump failed' message. I've had a look around and I'm almost able to do this how I want using "2> log_file.txt"

My original command:

mysqldump -u asdsa --password=$DB_PASS $DB_NAME > $MYSQL_LOCATION

if [ "$?" -eq 0 ]
then
echo -e "mysqldump successfully finished at $(date +'%d-%m-%Y %H:%M:%S')"$'\r' >> "$LOG_LOCATION"
else
echo -e "mysqldump failed at $(date +'%d-%m-%Y %H:%M:%S')"$'\r' >> "$LOG_LOCATION"
fi


So I added "2> $LOG_LOCATION |" to catch the actual error. So my updated command looks like this (this addition is in the first line):

mysqldump -u $DB_USER--password=$DB_PASS $DB_NAME 2> $LOG_LOCATION | > $MYSQL_LOCATION

if [ "$?" -eq 0 ]
then
echo -e "mysqldump successfully finished at $(date +'%d-%m-%Y %H:%M:%S')"$'\r' >> "$LOG_LOCATION"
else
echo -e "mysqldump failed at $(date +'%d-%m-%Y %H:%M:%S')"$'\r' >> "$LOG_LOCATION"
fi


This outputs the error to my log file but overwrites anything in there. It also means that my error checking if statement doesn't pick up the error.

Is there any way that I can:

a) catch the actual error from the mysqldump function (i.e. access denied for this user)
b) append this error to an existing error log
c) also append a success or fail message after the above error has outputted

Any help would be great!

Thanks!

Answer

So I added "2> $LOG_LOCATION |"

This is an error -- the pipe character is superfluous, and changes the meaning from a simple redirection into a pipeline.

Anyway, the proper way to use if is to run the actual command whose success you want to check as the condition.

if mysqldump -u "$DB_USER" --password="$DB_PASS" "$DB_NAME" 2>"$LOG_LOCATION" >"$MYSQL_LOCATION"
then
    echo -e "mysqldump successfully finished at $(date +'%d-%m-%Y %H:%M:%S')"$'\r' >> "$LOG_LOCATION"
else
    echo -e "mysqldump failed at $(date +'%d-%m-%Y %H:%M:%S')"$'\r' >> "$LOG_LOCATION"
fi

You are probably better off with printf over echo -e but I won't change those parts.

Comments