2012-11-14 86 views
3

我写了一些bash脚本来完成一些备份工作。我用errexit和pipefail运行脚本,所以我不会错过任何错误。我现在想要的是脚本向我发送一封电子邮件,以防发生错误。我得到了这个工作。但我希望将脚本错误包含在电子邮件正文中。我怎样才能做到这一点?bash通过邮件发送错误

这里是脚本:

#!/bin/bash 
# exit script if an error occures 
set -o errexit 
# even exit if an error in passed through a pipe 
set -o pipefail 

trap 'ERRORMESSAGE_HERE | mailx -s "Something went wrong on srv-002" [email protected]' ERR 

# the backup job here 

# if script reaches this point everything went perfectly good 
echo "all good!" 

非常感谢您的帮助!

+0

http://stackoverflow.com/questions/6784295/capturing-and-mailing-bash-script-errors - 这似乎是一个相关的问题,采取了看看答案是否适合你。 – Yuriy

回答

3

怎么样(未经测试):

{ 
    # do the work here 
} 2> >(mailx -s "job errors" [email protected]) 
+0

这应该起作用。或者,当你运行你的脚本时(如果你使用'cron'安排它)或者编写一个简单的包装器(如果你运行它),你可以追加'2>>(mailx -s“作业错误”[email protected])手动地)。 –

+0

我确认,它工作得很好!我的测试:'ls notExistingDir 2>>(mailx -s“作业错误”[email protected])' – Genjo