linux - 监控文件的 Bash 脚本

标签 linux bash shell

场景是 -

位置/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/

相关文章:

linux - vdebug-vim : not working

java - 如何将 Bash 与 Java 集成

shell - 从子 shell 退出 shell

linux - 错误退出从上一个错误延迟

linux - 启动后自动运行 flask 应用程序无法正常工作

bash - 如何使用 Robot 框架在 bash 中获取源文件?

bash - Unix 如何根据特定匹配对整行进行排序

python - 查找不包括测试用例的 Python 代码总行数

bash - 英镑符号 (£) 在 docker 容器内的 Bash shell 中产生新行

linux - 从 shell 脚本中的另一个文件读取命令?