简体   繁体   English

如何从分离的GNU屏幕会话中邮寄命令的输出?

[英]How can I mail a command's output from within a detached GNU screen session?

I am trying to write a bash script that executes a command in a screen session that displays the command's output in the session as well as emailing it when finished. 我正在尝试编写一个bash脚本,该脚本在screen会话中执行命令,该脚本在会话中显示命令的输出,并在完成后通过电子邮件发送该命令。 However, it doesn't always work and I can't work out why. 但是,它并不总是有效,我也不知道为什么。 I have distilled the behaviour to the below example: 我将行为提炼为以下示例:

The command 命令

ls | tee >(mail -s 'my subject' me@example.co.uk)

works fine every time, as does 每次都能正常工作,就像

bash -c "ls | tee >(mail -s 'my subject' me@example.co.uk)"

However, the command 但是,命令

screen -dmS foo bash -c "ls | tee >(mail -s 'my subject' me@example.co.uk)"

only works sometimes. 有时只能工作。

The reason for the command structure is that it's used in a cron-job to launch a script in a detached screen session (that a user can reattach to see the script's output in real-time) as well as emailing the output once the script completes. 命令结构的原因是,它在cron-job中用于在分离的screen会话中启动脚本(用户可以重新附加以实时查看脚本的输出),并在脚本完成后通过电子邮件发送输出。 I've replaced the script with ls in the examples to test and demonstrate the problem. 在示例中,我用ls替换了脚本,以测试和演示问题。

I use tail -f /var/log/mail.log to watch mails being dispatched. 我使用tail -f /var/log/mail.log来查看正在发送的邮件。 I performed the screen command ten times and only two mails were sent. 我执行了10次screen命令,仅发送了两封邮件。 To test a bit harder, I did this: 为了更严格地测试,我这样做:

for i in {1..100}; do screen -dmS test_$i bash -c "ls | tee >(mail -s 'screen test $i' me@example.co.uk)"; done

which resulted in 39 out of 100 mails being sent. 这样一来,每100封邮件中就有39封被发送。

This was originally done on OSX but I have also tested on a Linux box and see similar behaviour. 这最初是在OSX上完成的,但我也在Linux机器上进行了测试,并看到了类似的行为。 I think it has something to do with subshells in screen but I am not sure what the problem is. 我认为这与screen子外壳有关,但我不确定是什么问题。

What can be done to make this work? 如何做才能使这项工作?

I see this question was asked a long time ago but maybe my answer can help someone who finds these page for an answer(like me). 我看到这个问题是很久以前提出的,但是也许我的答案可以帮助找到这些页面的人找到答案(例如我)。

I had the same issue only I never get any mail with mail command from a detached screen session running as daemon with -dmS. 我有同样的问题,只是我从未从以-dmS作为守护程序运行的分离屏幕会话中收到任何带有mail命令的mail mutt command which is really similar to mail command tough solved my problem. mutt命令实际上类似于mail命令,解决了我的问题。 Here is how I send mail from the detached screen: 这是我从分离屏幕发送邮件的方式:

screen -dm -S "testMail" bash -c "echo body | mutt -s subject me@example.com"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM