Bash - if语句中的错误代码不起作用

时间:2014-05-04 01:39:58

标签: linux bash if-statement error-code

我正在编写一个bash脚本,它对已安装的驱动器进行备份。

备份本身工作正常但是即使在传输过程中出现错误,它也会说它成功。

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
}

尽管$ RETURNCODE给出值20,但它不会触发。输出低于。

安装备份驱动器 备份驱动器:/ dev / hda4已成功安装 将数据同步到/ dev / hda4

备份已成功完成,代码为20 Sun May 4 11:04:48 2014

所用时间:0h:0m:3s

如果有人有任何建议,我们将不胜感激:)

1 个答案:

答案 0 :(得分:3)

您确定backup_failed函数的行为符合预期吗?

另请注意,当RETURNCODE不为0且backup_failed未终止脚本时,backup_failed将被触发两次:

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

希望这有帮助。