如果不是每 30 分钟添加一次文件,我如何监视目录中的新文件并发送邮件?

Tec*_*hie 4 command-line bash scripts

我正在运行 Ubuntu 14.04,如果没有每 30 分钟添加一次新文件,我想监视一个文件夹并发送一封邮件。

我在下面也提到了。

如何监视目录中的新文件并将它们移动/重命名到另一个目录中?

我不确定如何等待一段时间并检查文件夹中的新文件。

ter*_*don 7

你也许可以做一些简单的事情:

#!/bin/bash
targetDir="$1"
while true; do
  files=("$targetDir"/*)
  sleep 30m ## wait 30 minutes
  files1=("$targetDir/"*)
  if [[ ${#files[@]} == ${#files1[@]} ]]; then
     echo "No new files added" | mail user@example.com
  fi
done
Run Code Online (Sandbox Code Playgroud)

将该脚本另存为~/bin/watch.sh或您喜欢的任何内容,使其可执行 ( chmod a+x ~/bin/watch.sh) 并运行它,并将目标目录作为参数:

watch.sh /path/to/dir
Run Code Online (Sandbox Code Playgroud)

现在,这是一种非常幼稚的方法,只是每 30 分钟计算一次文件数。因此,如果删除了一个文件但添加了另一个文件,它会认为没有新文件。获取最新文件的时间戳并检查它是否在 30 分钟前被上次修改可能是一个更好的主意:

#!/bin/bash
targetDir="$1"
newest=0;

while true; do
  ## Wait for half an hour. This is done at the beginning of the loop
  ## to ensure we wait a half hour before the first check
  sleep 30m
  ## Get the current time in seconds since the epoch
  now=$(date '+%s')
  for file in "$targetDir"/*; do
    ## Get the file's modification time in seconds since the epoch
    lastMod=$(stat -c "%Y" "$file")
    ## Is this file newer than the current newest?
    if [[ $lastMod -gt $newest ]]; then
      newest=$lastMod
    fi
  done
  ## If the newest file is older than half an hour
  if [[ $((now - newest)) -gt 1800 ]]; then
    echo "No new files added since $(date -d '- 30 min')" |
      mail user@example.com
  fi
done
Run Code Online (Sandbox Code Playgroud)

如果您不想永远这样运行脚本,您可以编写一个检查时间戳并每 30 分钟调用一次脚本的脚本:

#!/bin/bash
targetDir="$1"
newest=0;

for file in "$targetDir"/*; do
  ## Get the file's modification time in seconds since the epoch
  lastMod=$(stat -c "%Y" "$file")
  ## Is this file newer than the current newest?
  if [[ $lastMod -gt $newest ]]; then
    newest=$lastMod
  fi
done
## Get the current time in seconds since the epoch
now=$(date '+%s')
## If the newest file is older than half an hour
if [[ $((now - newest)) -gt 1800 ]]; then
    echo "No new files added since $(date -d '- 30 min')" |
     mail user@example.com
fi
Run Code Online (Sandbox Code Playgroud)

现在,将其另存为~/bin/watch.sh并使其可执行 ( chmod a+x ~/bin/watch.sh)。然后,运行crontab -e并添加以下行:

*/30 * * * * /home/techie/bin/watch.sh
Run Code Online (Sandbox Code Playgroud)

保存文件(保存会添加 crontab)并完成。该脚本将每 30 分钟运行一次。