1

I have created the following shell scrip to backup MySQL DB, zip it, and then copy it to an s3 bucket:

#vim /home/ubuntu/backup/mysqlbackup2.sh

#!/bin/bash
## Backup mysql DB, zip it and then copy it to s3 bucket

mysqldump -hhostname -uusername dbName -p'p@ssW0rd' > db.sql

if [ $? -le 1 ] 
then
    # zip the file and copy it s3 bucket
    sudo gzip -9 db.sql
    s3cmd put db.sql.gz s://mys3bucket/
else 
    echo "Fail to backup MySQL DB" >> "backup.log"
fi

It does everything fine and the backup is copied to s3 bucket. But I cannot understand the output of shell script:

enter image description here

I understand the password warning but why does it show: '[' 0 -le 1 ']'? Is there anything wrong in my if condition?

dessert
  • 39,982
  • 1
    There’s no need to have sudo inside the script (and that’s actually not a good practice, see https://askubuntu.com/q/425754/507051) if you run the whole script as root. – dessert May 21 '19 at 04:57
  • Like @desert said you will need to changer two things in your script those wold be 1) remove "sudo" and 2) make the "-le" option "-lt" and this is what you most likely want. – George Udosen May 21 '19 at 05:27
  • @GeorgeUdosen: thanks, I have removed sudo. But mysqldump returns 1 (warning), because of using the command line password... I wasn't sure how to get around that. – Hooman Bahreini May 21 '19 at 05:29
  • That should be coming from the mysqldump line. Run that alone to see what gives. – George Udosen May 21 '19 at 05:34
  • OK, I see. I thought $? is getting the exit status of mysqldump. Is that not the case? – Hooman Bahreini May 21 '19 at 05:37
  • It is, I think you two are misunderstanding each other. See my comment on the answer for an approach to test for 0 or 1 explicitly. – dessert May 21 '19 at 05:44
  • I changed the condition to [ $? -eq 0 ] and it's working. Thanks a lot. – Hooman Bahreini May 21 '19 at 06:05

1 Answers1

3

Your script:

mysqldump -hhostname -uusername dbName -p'p@ssW0rd' > db.sql

if [ $? -lt 1 ] #<-- if the script exit status value is less than or equal 1, which means it succeeded then execute the if block
then
    # zip the file and copy it s3 bucket
    gzip -9 db.sql #<-- create a zipped folder from the mysql backup file
    s3cmd put db.sql.gz s://mys3bucket/ #<-- Amazon http request PUT command
else 
    echo "Fail to backup MySQL DB" >> "backup.log" #<-- if the backup failed let us know by out putting this message into the backup.log file
fi

'[' 0 -le 1 ']': A zero here means the the command to backup succeeded, and reads "less than or equal to". And yes those lines with a "+" are showing you the various steps in the execution process and that is because you used the -x in the option in executing the bash script.

Also as noted by desert the sudo and the "-le" option should be removed and changed to "-lt" respectively.

George Udosen
  • 36,677