场景是 -
在位置/opt/data/中有10个差异文件,名称以前一天结尾
例如 - file_1_20160627
我需要检查这10个文件是否存在。
如果存在,我需要显示输出 - “确定 - file_1_20160627 存在” 并将输出写入/tmp/report.txt 文件
如果文件不存在,我想要与上面相同的内容 - “失败 - file_1_20160627 不存在” 和 将输出写入同一/tmp/report.txt 文件
脚本每天运行时,该文件上的内容都必须替换。
我尝试过写作,但我不擅长编写脚本。下面的脚本仅适用于 4 个文件。我认为很多事情都需要改变。
感谢有人帮助我创建此脚本。
#!/bin/bash
now=`date +%Y%m%d%H%M%S`
time=`date +%H%M`
week=`date +%a`
/bin/rm -f /tmp/report.txt
if [ "$time" -ge 1300 ] && [ $time -lt 2359 ]; then
if [ "$week" == Sun ]; then
if [ -f "find /opt/data/ -type f -name "file_1_`date -d "1 day ago" +%Y%m%d`.txt"" ];
then
echo "OK - file_1 file does exist" >> /tmp/report.txt
else
echo "Failed - file_1 file does not exist." >> /tmp/report.txt
fi
if [ -f "find /opt/data/ -type f -name "file_2_`date -d "1 day ago" +%Y%m%d`.txt"" ];
then
echo "OK - file_2 file exist." >> /tmp/report.txt
else
echo "Failed - file_2 file does not exist" >> /tmp/report.txt
fi
else
fi
if [ -f "find /opt/data/ -type f -name "file_3_`date -d "1 day ago" +%Y%m%d`.txt"" ];
then
echo "OK - file_3 file exist" >> /tmp/report.txt
else
echo "Failed - file_3 file does not exist" >> /tmp/report.txt
fi
if [ -f "find /opt/data/ -type f -name "file_4_`date -d "1 day ago" +%Y%m%d`.txt"" ];
then
echo "OK - file_4 file exist" >> /tmp/report.txt
else
echo "Failed - file_4 file does not exist" >> /tmp/report.txt
fi
else
fi
最佳答案
PREFIX="/opt/data"
REPORT="/tmp/report.txt"
DATE=$( date +%Y%m%d )
rm "$REPORT"
for i in `seq 1 10`;
do
FILENAME="file_${i}_${DATE}"
FULLFN="$PREFIX/$FILENAME"
if [ -f "$FULLFN" ]; then
echo "OK - $FILENAME exists" >> $REPORT
else
echo "Failed - $FILENAME do not exist" >> $REPORT
fi
done
关于linux - 监控文件的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38083986/