Detecting mysqldump error in bash script

I am currently trying to write a script that maintains several of my sites along with their databases.

Everything works well, but I'm trying to be a little smarter with my log - basically, for now, it will try to start mysqldump and echo success or failure.

What I would rather do is print the actual error rather than just the useless "mysqldump failed" message. I have looked around and I am almost able to do it as I want to use "2> log_file.txt"

My initial 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 on 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 an error to my log file, but overwrites something there. This also means that my error checking if the statement is not executing does not throw an error.

Is there a way I can:

a) catch the actual error from the mysqldump function (i.e. access is denied for this user) b) add this error to the existing error log c) also add a success or failure message after the above error has thrown

Any help would be great!

Thank!

+3


source to share


2 answers


So I added "2> $ LOG_LOCATION |"

This is an error - the pipe symbol is redundant and changes the value from a simple redirect to a pipe.

In any case, the correct way to use it if

is to run the actual command, the success of which you want to test as a 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're probably better off with printf

over echo -e

, but I won't change those parts.

+7


source


a) You can catch the error output in a variable like this:

somevar="$( ( mysqldump -u $DB_USER --password=$DB_PASS $DB_NAME > $MYSQL_LOCATION ) 2>&1 )"

      

b) You can view the contents of this variable, display the message as usual, and



c) You can easily forward it to your log file with echo "$somevar" >> $LOG_LOCATION

Hello

+4


source







All Articles