*注意我编辑了这个,所以我的最终功能代码在
之下好的所以我正在编写一个bash脚本来将我们的mysql数据库备份到一个目录,如果存在10则删除最旧的备份,并将备份结果输出到日志中,这样如果失败就可以进一步创建警报。一切都很好,除了if循环输出结果,再次感谢帮助人员代码在下面!
#! /bin/bash
#THis creates a variable with the date stamp to add to the filename
now=$(date +"%m_%d_%y")
#This moves the bash shell to the directory of the backups
cd /dbbkp/backups/
#Counts the number of files in the direstory with the *.sql extension and deletes the oldest once 10 is reached.
[[ $(ls -ltr *.sql | wc -l) -gt 10 ]] && rm $(ls -ltr *.sql | awk 'NR==1{print $NF}')
#Moves the bash shell to the mysql bin directory to run the backup script
cd /opt/GroupLink/everything_HelpDesk/mysql/bin/
#command to run and dump the mysql db to the directory
./mysqldump -u root -p dbname > /dbbkp/backups/ehdbkp_$now.sql --protocol=socket --socket=/tmp/GLmysql.sock --password=password
#Echo the results to the log file
#Change back to the directory you created the backup in
cd /dbbkp/backups/
#If loop to check if the backup is proper size and if it exists
if find ehdbkp_$now.sql -type f -size +51200c 2>/dev/null | grep -q .; then
echo "The backup has run successfully" >> /var/log/backups
else
echo "The backup was unsuccessful" >> /var/log/backups
fi
答案 0 :(得分:4)
或者,您可以使用stat
代替find
。
if [ $(stat -c %s ehdbkp_$now 2>/dev/null || echo 0) -gt 51200 ]; then
echo "The backup has run successfully"
else
echo "The backup was unsuccessful"
fi >> /var/log/backups
选项-c %s
告诉stat
以字节为单位返回文件大小。这将同时处理大于51200的文件和大小。当文件丢失时,stat
将错误,因此我们将错误消息重定向到/dev/null
。逻辑或条件||
将仅在文件丢失时执行,因此比较将使[ 0 -gt 100 ]
为假。
答案 1 :(得分:2)
要检查文件是否存在且大于51200字节,您可以像这样重写if
:
if find ehdbkp_$now -type f -size +51200c 2>/dev/null | grep -q .; then
echo "The backup has run successfully"
else
echo "The backup has was unsuccessful"
fi >> /var/log/backups
其他说明:
find
一次关注两件事:检查文件是否存在且大小是否大于51200. /dev/null
以隐藏错误消息。grep
将匹配并成功退出,否则将以失败退出grep
的最终结果是决定if
条件>> /var/log/backups
之后移动fi
,因为它相当于这种方式,减少了重复。 Btw if
不是一个循环,它是一个有条件的。
<强>更新强>
正如@glennjackman指出的那样,更好的方式来编写if
,而不是grep
:
if [[ $(find ehdbkp_$now -type f -size +51200c 2>/dev/null) ]]; then
...