Archive

Posts Tagged ‘standard output’

Redirect output to file

March 9th, 2009 No comments

Normally when you execute a command in your shell you’ll get the output direct on your screen. But it’s also possible to redirect this output to a file, for example for logging purposes.

Example:

php myscript.php > mylog.log

Now all output from myscript.php will go in the mylog.log file. This is called the “standard output” (stdout). But when a PHP error occurs it will not be written to the mylog.log file. Instead it will be printed on your screen. This is the “error output” (stderr), and to write this to mylog.log you have to use this:

php myscript 2>&1 mylog.log

This will send all output to mylog.log including the errors. It’s also possible to only write the error ouput to a log file.

php myscript 2> mylog.log

Combine this with ‘running processes as background jobs ‘ and you can run your scripts/command in the background but still be able to watch the progress in the log file.

php myscript 2>&1 mylog.log &

And now watch your log with

tail -f mylog.log

You will see new lines being written to the log in real time!

These different outputs are streams, read more info about this here.