简体   繁体   中英

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. 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. I've replaced the script with ls in the examples to test and demonstrate the problem.

I use tail -f /var/log/mail.log to watch mails being dispatched. I performed the screen command ten times and only two mails were sent. 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.

This was originally done on OSX but I have also tested on a Linux box and see similar behaviour. I think it has something to do with subshells in screen but I am not sure what the problem is.

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. mutt command which is really similar to mail command tough solved my problem. Here is how I send mail from the detached screen:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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