Bash 脚本可在添加新文件时监视多个路径并结束电子邮件通知

问题描述

我编写了一个脚本来监视 2 个目录并在此处添加文件时结束电子邮件通知,但它似乎只监视第一个目录而不是第二个目录(当我没有收到通知时在第二个目录中添加一些东西),谁能帮我解决这个问题? 脚本:

#!/bin/bash

monitor_dir=/path1/UnSent
monitor_dir1=/path2/Failed

email=email1.com
email2=email2.com


files=$(find "$monitor_dir" -maxdepth 1 | sort)
IFS=$'\n'

while true
do
  sleep 5s

  newfiles=$(find "$monitor_dir" -maxdepth 1 | sort)
  added=$(comm -13 <(echo "$files") <(echo "$newfiles"))

  [ "$added" != "" ] &&
    find $added -maxdepth 1 -printf '%Tc\t%s\t%p\n' |
    mail -s "your file sent to UnSent" "$email" 

  files="$newfiles" 
done

files1=$(find "$monitor_dir1" -maxdepth 1 | sort)
IFS=$'\n'

while true
do
  sleep 5s

  newfiles1=$(find "$monitor_dir1" -maxdepth 1 | sort)
  added=$(comm -13 <(echo "$files1") <(echo "$newfiles1"))

  [ "$added" != "" ] &&
    find $added -maxdepth 1 -printf '%Tc\t%s\t%p\n' |
    mail -s "your file sent to Failed" "$email2" 

  files1="$newfiles1" 
done

解决方法

在第一个循环 & 之后添加一个与符号 done & 可能会有所帮助。这将在后台运行第一个循环并继续第二个循环。没有 &,第二个循环将永远不会到达,因为第一个循环无限期地运行。

更新后的代码:

#!/bin/bash

monitor_dir=/path1/UnSent
monitor_dir1=/path2/failed

email=email1.com
email2=email2.com


files=$(find "$monitor_dir" -maxdepth 1 | sort)
IFS=$'\n'

while true
do
  sleep 5s

  newfiles=$(find "$monitor_dir" -maxdepth 1 | sort)
  added=$(comm -13 <(echo "$files") <(echo "$newfiles"))

  [ "$added" != "" ] &&
    find $added -maxdepth 1 -printf '%Tc\t%s\t%p\n' |
    mail -s "your file sent to UnSent" "$email" 

  files="$newfiles" 
done &

files1=$(find "$monitor_dir1" -maxdepth 1 | sort)
IFS=$'\n'

while true
do
  sleep 5s

  newfiles1=$(find "$monitor_dir1" -maxdepth 1 | sort)
  added=$(comm -13 <(echo "$files1") <(echo "$newfiles1"))

  [ "$added" != "" ] &&
    find $added -maxdepth 1 -printf '%Tc\t%s\t%p\n' |
    mail -s "your file sent to failed" "$email2" 

  files1="$newfiles1" 
done