【问题标题】:If either of the files exist then send email alert in bash shell script如果其中任何一个文件存在,则在 bash shell 脚本中发送电子邮件警报
【发布时间】:2016-06-23 04:14:00
【问题描述】:

试图模拟一个小 shell 脚本.. 已经存在一个创建两个文件之一的进程(即 file1 或 file2)。我的目标是能够根据创建的文件发送电子邮件警报。

例如,如果 file1 存在,则向 John、David、Smith 发送电子邮件,说明 file1 已创建。如果 file2 存在,则向同一组人(John、David、Smith)发送一封电子邮件,说明 file2 已创建。

如果我编写一个简单的 if-else,它会起作用,但我需要重复一些我试图避免的代码部分。

#!/bin/bash
file="file1"
if [ -f "$file1" ]
    then
        send email to three people mentioned 
    else
        send email to three people mentioned saying file2 was created since it always creates two files 
    fi
}

在这里,我正在尝试以更好的方式构建脚本,并且我不想重复三次“发送电子邮件...”命令,因为将来我可能需要将更多人添加到列表中。

请帮忙。提前致谢。

【问题讨论】:

  • 虽然我无法说出任何名字,但已经有一些可用的软件包可以监视目录的更改并生成各种警报。您是否尝试过在 Internet 上搜索“目录监视器”?

标签: linux shell email unix


【解决方案1】:

您可以创建一个功能块,将邮件发送到所需的人员列表。从任一案例中调用该功能

【讨论】:

  • 目录监视器 - 我不知道如何构建一些东西来满足我的需求
  • 恐怕我还没有使用过任何一种情况下都可以调用的函数。在我看来,这样做会更容易。是否有任何我可以使用的模板能够根据文件(file1/file2)是否存在来发送警报?赞赏。
【解决方案2】:

类似

#!/bin/bash

userlist="$HOME/myusers.cfg" # one user per line

function send_alert {
   while read -r user comment; do
      echo "my command to send to ${user}"
      echo "subject=$1"
      echo "Content=Hello ${comment}\n$2"
   done < "${userlist}"
}

file="file1"
if [ -f "$file1" ]; then
   send_alert "My subject" "Content: ${file1} exists."
else
   send_alert "My subject" "Content: ${file2} exists."
fi

我在 myusers.cfg 中添加了一个可选字段注释,因此您可以在空格后添加一些注释(姓名、人物)。
您可以调整 send_alert 以获得更多业务规则,例如每小时只发送一次警报,只在工作时间发送,除了夜班的人,等等。

【讨论】:

  • 非常感谢。我会运行它,看看我是否可以满足我的要求
猜你喜欢
  • 2018-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 2011-08-09
  • 1970-01-01
  • 2010-12-21
相关资源
最近更新 更多