Unix tips: handling script output

Wow I've not blogged in ages! Here's a couple of quickies that I seem to rediscover every 6 months and promptly forget - hopefully writing them here will make them stick in my head.

Logging output to disk

Obviously to log the output of some process to disk you'd normally use > or >>. However, sometimes you want to also use the output for some other process.

In instances like this you'd use tee:

php my-script.php | tee -a /var/log/my-script.log | other-script

The output of my my-script.php will be both written to my my-script.log, and piped to other-script for further processing (the -a flag means the output is appended to the log rather than it being overwritten).

Emailing output when something happens

The mail command provides a simple way to mail the output of a script:

php myscript.php | mail -s "A subject line" address@example.com

However this gets annoying when your script runs every 5 minutes, so more recent implementations of mail have a -E flag that only sends the mail if the output wasn't empty:

php myscript.php 2&>1 | mail -E -s "A subject line" address@example.com

In this example the mail will only be sent if myscript.php output something (or an error, the 2&>1 redirects its error output to its standard output).

Unfortunately commenting is currently disabled, so hit me on twitter @CiaranMcNulty if you have any other tips for what to do with output and I'll maybe write a follow-up article.

Bookmark and Share

Comments

Commenting is currently disabled