The Curious Website Designer

Bash - How to Send stdout & stderr To a Logfile

Posted by The Curious Website Designer | Posted on Sat 28 Apr 2018

Bash - How to Send stdout & stderr To a Logfile

Debugging CRON jobs can be quite difficult - there is no visible output, so you don't know if the script failed to run or if the script ran but failed. If it's the latter (ran and failed), you don't get to see any error messages.

If the script is a PHP script, I usually include a standard debug function which allows me to record various checkpoints within the script. These may take the form of comments such as 'Reached point x of the script', or contents of variables eg 'Variable $x contains "abcde12345" '.

However, if the script is a Bash script, you can send the content of stdout and stderr to a logfile. In fact, you can send both outputs to separate files if you wish.

stdout is any output that would normally be sent to the screen in a PuTTY window when a command is run. stderr is any error message generated if there is a problem with the command.

Here is the syntax to use:

Send stdout to a logfile (instead of the terminal):

command > logfile.log

 

To append stdout to a logfile use:

command >> logfile.log

 

To send stdout and stderr to the same logfile:

command > logfile.log 2>&1

 

To send stdout and stderr to different log files use:

command > logfile.log 2 > second_logfile.log

 

 

Related Articles

Bash - How To Recursively CHMOD Files And Folders

Bash - How To Recursively CHMOD Files And Folders

Posted by: The Curious Website Designer
on Sun 10 Jan 2021

Occasionally, especially after extracting an archive, the file and folder permissions are not as they should be; I had a recent example where many files were left with 640 permission instead of 644. As a reminder to myself, here's how to do it.

Bash - Recursively Removing Files and Folders

Bash - Recursively Removing Files and Folders

Posted by: The Curious Website Designer
on Sun 10 Jan 2021

Another reminder how to perform a routine task from the command line or in a Bash script. This time it's deleting files & folders. Also how to remove a group of files that are older than (x) days.