user3600401
user3600401

Reputation: 13

Bash - error code in if statement not working

I am writing a bash script which does a backup to a mounted drive.

The backup itself works fine however even if there is an error during transfer it will say its successful.

backup() {
echo -e "Backup Started\n" >> $1
echo -e "Mounting backup Drive" >> $1
mount $2 /mnt 2>>$1
if [ $? -eq 0 ] ; then
   echo -e "Backup Drive: $2 mounted successfully" >> $1
   cd /
   echo -e "Sync data to $2\n" >> $1
   nice -n 19 rsync -lHa --exclude-from '/opt/ts/bin/exclude.txt' / /mnt/ 2> ${ERROR}
   local RETURNCODE=$?
   if [ $RETURNCODE -eq 23 ] ; then backup_failed "Backup Warning: Some files did not copy" $1 $2; fi
   if [ $RETURNCODE -eq 20 ] ; then backup_failed "Backup Failed: Transfer was terminated prematurely" $1 $2; fi
   if [ $RETURNCODE -eq 11 ] ; then backup_failed "Backup Failed: Input/Output Error [URGENT]" $1 $2; fi
   if [ $RETURNCODE -ne 0 ] ; then backup_failed "Backup Failed: Error while copying data" $1 $2; fi
   echo -e "Backup completed Successfully with code $RETURNCODE `date`\n" >> $1
   echo -e >> $1
   printf "Time taken: "%dh:%dm:%ds"\n" $(($SECONDS/3600)) $(($SECONDS%3600/60)) $(($SECONDS%60)) >> $1
   echo -e "##############################\n" >> $1
   mkdir -p /mnt/mnt /mnt/proc /mnt/tmp /mnt/lost+found
   cp -a /proc/mounts /proc/filesystems /mnt/proc
   umount $2
fi
}

Despite $RETURNCODE giving a value of 20 it does not trigger. Output is below.

Mounting backup Drive Backup Drive: /dev/hda4 mounted successfully Sync data to /dev/hda4

Backup completed Successfully with code 20 Sun May 4 11:04:48 EST 2014

Time taken: 0h:0m:3s

#

If anyone has any suggestions it would be appreciated :)

Upvotes: 1

Views: 533

Answers (1)

pah
pah

Reputation: 4778

Are you sure that the function backup_failed is behaving as expected?

Also note that backup_failed will be triggered twice when RETURNCODE is not 0 and backup_failed doesn't terminate the script:

if [ $RETURNCODE -eq 20 ] ; then backup_failed ...
...
if [ $RETURNCODE -ne 0 ] ; then backup_failed ...

Hope this helps.

Upvotes: 3

Related Questions