lundi 31 juillet 2017

bash variable's if then statement not evaulating correctly

I have written a script that should tell me the number of lines from the nightly network backups. It should be 109 and if it is the same I get success email and if it is not the same I get a failure email. I have added 2 fake host to one of the files that is checked in the script below to see if it will fail. The if then statement simply does not work. If I make the amount of hosts in the file's 'confirm-backed-up' and 'backed-up' different it makes no difference and it just uses the very first if then statement regardless if they are different or not.

At the end you can see I ran the wc -l on the two files and they are different however the script runs and gives me the first then of the if, then: backed-up and confirm-backed-up match. It goes the other way also - if they are the same I just get the first if then statement - which at first made me think it was working until I checked it with the files not matching in number.

#!/bin/bash

# Variables
date=`date +%Y%m%d`
o1=$(cat /netops/backups/scripts/hostfiles/backed-up | wc -l)
o2=$(cat /netops/backups/scripts/hostfiles/confirm-backed-up | wc -l)
sdir=/netops/backups/storage/
hostdir=/netops/backups/scripts/hostfiles

# Functions

function confirm_backup
{
find $sdir -type f -mtime 0 -printf '%f\n' |grep $date >$hostdir/backed-up
cat $hostdir/cisco-nexus.txt >> $hostdir/confirm-backed-up
cat $hostdir/cisco-firewall.txt >> $hostdir/confirm-backed-up
cat $hostdir/esx.txt >> $hostdir/confirm-backed-up
cat $hostdir/f5.txt >> $hostdir/confirm-backed-up
cat $hostdir/fortigate.txt >> $hostdir/confirm-backed-up
cat $hostdir/rsa.txt >> $hostdir/confirm-backed-up
cat $hostdir/sw-no-pk.txt >> $hostdir/confirm-backed-up
cat $hostdir/switch-router.txt >> $hostdir/confirm-backed-up
cat $hostdir/tlite.txt >> $hostdir/confirm-backed-up
}

# Verify Backup

function backup_verify
{
if [ "echo $o1" == "echo $o2" ]; then # I tried this with if [ "$o1" == "$o2"] also & if (( $o1 != $o2 )) & [ "$o1" = "o2" ] - all same results.
echo "backed-up and confirm-backed-up match" & mail -s "All Backups   succeeded" 12345566@blah.net   < /dev/null
else
echo "a backup has failed" & mail -s "A backup failed" 123456789@vtext.com  < /dev/null
fi
}

# Start Script Run

confirm_backup
backup_verify
cat /dev/null > $hostdir/confirm-backed-up # this is here for long term - i tested it with this gone so otherwise obviously my wc -l would have been 0
cat /dev/null > $hostdir/backed-up

user@host:/netops/backups/scripts$ ./test6.sh 
backed-up and confirm-backed-up match
Null message body; hope that's ok # WRONG!
user@host:/netops/backups/scripts$ cd hostfiles/
user@host:/netops/backups/scripts/hostfiles$ wc -l backed-up 
109 backed-up # so I check manually
user@host:/netops/backups/scripts/hostfiles$ wc -l confirm-backed-up 
111 confirm-backed-up # the files are different.

Aucun commentaire:

Enregistrer un commentaire