3
mysqldump --verbose -h $dbhost --max_allowed_packet=1G --extended- 
insert --single-transaction --add-drop-database --opt $dbname -- 
user=$dbusername --password=$dbpassword | gzip -1 > $filename.sql.gz
echo $?

I'm using the above code in my bash script to take a mysql dump and gzip it.

I want to confirm the mysqldump was successful before allowing the script to continue running. If for example the host isn't found how can i catch that error?

I am unsure as to how to achieve this. Current output i get with the above is as follows:

mysqldump: Got error: 2005: Unknown MySQL server host 'test' (0) when
trying to connect 
0

why am i getting a 0 success code when the host wasn't found? I think it's because the gzip is still successful in that it produces an empty file...but i dont know how to work around this.

gurpsone
  • 463
  • 7
  • 17

2 Answers2

3

When pipe (|) is used, the exit value of the last command of the pipeline is only captured. But we can workaround this by using set -o pipefail. This captures non zero exit code in the pipeline

Make your schell script like this always

#!/bin/bash
set -o pipefail

example:

C02MLC76FD57:~ vkrishna$ cat testing.sh
#!/bin/bash
set -o pipefail
false | echo "hello world"
echo $?

C02MLC76FD57:~ vkrishna$ ./testing.sh
hello world
1

The exit status of false is always 1.

(or)

You can also use PIPESTATUSas below

$ false | true
$ echo "${PIPESTATUS[0]} ${PIPESTATUS[1]}"
1 0

I prefer to go with set -o pipefail in shell scripts.

And

regarding capturing the error, while executing the script redirect the stderr to a file to capture the actual error.

Example: file name is backup.sh

./backup.sh 2>/tmp/backupError.log

This way if backup works, everything good and if it fails we captured the error.

vkrishna
  • 744
  • 1
  • 6
  • 10
2

Do you mean something like this

 #!/bin/bash
    mysqldump --verbose -h $dbhost --max_allowed_packet=1G --extended- 
insert --single-transaction --add-drop-database --opt $dbname -- 
user=$dbusername --password=$dbpassword | gzip -1 > $filename.sql.gz
    if [ "$?" -eq 0 ]; then
        echo "mysqldump command Successful"    
    else
        echo "mysqldump encountered an Error"
    fi

You can do the following to check for mysql error and continue with gzip compression

#!/bin/bash
mysqldump --verbose -h $dbhost --max_allowed_packet=1G --extended- 
    insert --single-transaction --add-drop-database --opt $dbname -- 
    user=$dbusername --password=$dbpassword > db.dump
if [[ $? -eq 0 ]]; then
    gzip db.dump
else 
    echo >&2 "DB backup failed" 
    exit 1
fi
unixmiah
  • 3,081
  • 1
  • 12
  • 26
  • 1
    yes, exactly, however, i always get a successful message because the gzip command which is the last command that ran, is successful even though mysqldump fails. – gurpsone Sep 06 '18 at 19:50
  • @gurpsone check my answer. I've updated it. – unixmiah Sep 06 '18 at 19:53