How to Log All Script Output Inside the Script Itself
Logging script output is a common practice in shell scripting to keep track of what a script is doing, especially during debugging or troubleshooting. In this guide, we’ll show you how to log all script output inside the script itself using the tee command and redirection.
Here’s a simple example of a script that echoes some text and logs its output:
|
|
In this script:
-
We specify the path to the debug log file using the
DEBUGLOGvariable. Make sure to replace/path/to/debug.logwith the actual path and filename where you want to store the log. -
Inside the script block enclosed by
{}braces, we have some sample commands (echo statements) that generate output. You can replace these with your own script logic. -
The
2>&1redirects the standard error (file descriptor 2) to the same location as standard output (file descriptor 1). This ensures that both stdout and stderr are captured and logged. -
The
teecommand is used to duplicate the output stream. It reads from the previous command (the block of echo statements) and simultaneously writes to both the terminal (stdout) and the specified log file. The-aoption is used withteeto append to the log file if it already exists. -
After logging the output, you can continue with the rest of your script logic.
To use this script:
- Save the script to a file (e.g.,
my_script.sh). - Make the script executable by running
chmod +x my_script.sh. - Run the script using
./my_script.sh. The script’s output will be displayed on the terminal, and a copy of the output will be appended to the specified log file (/path/to/debug.log).
Now, whenever you execute the script, all of its output will be logged in the specified log file for later analysis or debugging.