我写了一个脚本,应该告诉我夜间网络备份的行数。它应该是109,如果它是相同的,我会收到成功的电子邮件,如果不一样,我会收到一封失败的电子邮件。我已将2个虚假主机添加到下面的脚本中检查的文件之一,以查看它是否会失败。 if then语句根本不起作用。如果我在文件'确认备份'和'备份'中的主机数量不同,它就没有区别,只要使用第一个if语句,无论它们是否不同。bash变量的如果然后语句不正确地计算
最后你可以看到我在两个文件上运行了wc -l,但它们不同,但脚本运行并给了我第一个if,then:备份和确认备份匹配。它也以另一种方式 - 如果它们是相同的,我只是得到第一个如果然后声明 - 起初让我觉得它工作,直到我检查与数量不匹配的文件。
#!/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
#功能
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" [email protected] < /dev/null
else
echo "a backup has failed" & mail -s "A backup failed" [email protected] < /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
[email protected]:/netops/backups/scripts$ ./test6.sh
backed-up and confirm-backed-up match
Null message body; hope that's ok # WRONG!
[email protected]:/netops/backups/scripts$ cd hostfiles/
[email protected]:/netops/backups/scripts/hostfiles$ wc -l backed-up
109 backed-up # so I check manually
[email protected]:/netops/backups/scripts/hostfiles$ wc -l confirm-backed-up
111 confirm-backed-up # the files are different.
通过http://shellcheck.net/运行你的代码并修复它发现的内容。在这些问题中 - 如果你实际上是用bash以外的shell调用的话,'=='不能保证工作;由POSIX标准指定的比较运算符是'='。 –
这就是说 - 你想比较两个文件,而不是两个变量?你应该使用'cmp'。没有任何意义的是将字符串“echo”作为前缀的两个值。 –
另外 - 使用'bash -x yourscript'来记录每个命令来运行你的脚本。通过这种方式,你可以准确地判断出**正在测试的值是什么。 –