In the following script I'm iterating through four different paths and running a custom command (here named : /usr/bin/mycommand).
I'm trying to restart that command automatically three times over in case it fails by using a while loop based on the command's exit code.
If the command fails despite restarting it three times, it writes the failure notification in an temporary file which the script sends to me via email at the end.
The issue is that if several paths fail I still only get one notification line in my email (the latest path failure) and I can't figure out why.
#!/bin/bash
## Variables
email="recipient@email.com"
localsrv='srv1'
remotesrv='srv2'
emailbody='/tmp/content.txt'
paths=( path1 path2
path3 path4
)
for path in "${paths[@]}" ; do
xcmd=0
/usr/bin/mycommand $path
status=$?
while [ $status -ne 0 ]
do
/bin/echo "Failure. Restarting command for path $path..."
xcmd=$(( $xcmd + 1 ))
/bin/echo "Waiting for 60 seconds before retrying..."
/bin/sleep 60s
/usr/bin/mycommand $path
status=$?
if [ $xcmd -eq 3 ]; then
/bin/echo "Three failures for path $path. Skipping." >> $emailbody
break
fi
done
done
if [ -s $emailbody ]; then
/bin/echo "Backup finished" >> $emailbody
/bin/mail -s "Failure report from server $localsrv" $email < $emailbody
/bin/rm $emailbody
else
/bin/printf "Success!\nBackup finished\n" | /bin/mail -s "Success report from server $localsrv" $email
/bin/rm $emailbody
fi