bash 如果文件不为空,我如何编写一个 shell 脚本,该脚本将通过电子邮件发送给我?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1169612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:04:35  来源:igfitidea点击:

How can I write a shell-script that will email me a file if the file is not empty?

bashemailshell

提问by Hintswen

I'm looking for a script I can run to check if a text file is empty, if it is then do nothing but if it has something in it, I want it to send me an email with the text file as the message. No idea how to do it.

我正在寻找一个脚本,我可以运行它来检查文本文件是否为空,如果是空的,则什么都不做,但如果其中有内容,我希望它向我发送一封包含文本文件作为消息的电子邮件。不知道该怎么做。

回答by Leigh Gordon

[ -s "$f" ] && mail [email protected] -s "$f contents" < $f

Nice and compact :)

漂亮而紧凑:)

回答by zoul

For example:

例如:

test -s your_file && mutt -a your_file -s "Sending you a file" [email protected]

This will send the file as attachment. If you want to include the file in the message body, you can use the -iswitch instead of the -a. If you don't have Mutt installed you can call mail:

这会将文件作为附件发送。如果要在消息正文中包含文件,可以使用-i开关代替-a. 如果你没有安装 Mutt,你可以调用mail

test -s your_file && mail -s "Sending you a file" [email protected] < your_file

回答by jabbie

As a script

作为脚本

#!/bin/bash
file=file_to_check
if [ -s ${file} ] ; then
  mail -s "The file is not empty!" [email protected] < $file
fi

Or in one line. (To put in a crontab)

或者在一行中。(放入 crontab)

   [ -s file_to_check ] && mail -s 'File is not empty' [email protected] < file_to_check

回答by Hyman Leow

Something like this should work.

像这样的事情应该有效。

if [ `wc -l file.txt` -gt 0 ]; then
    mail root@localhost < file.txt
fi