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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/bin/bash

# Define the path to the debug log file
DEBUGLOG="/path/to/debug.log"

# Redirect all output (stdout and stderr) to the debug log using tee
{
    echo "test"
    echo "test 2"
    echo "test 3"
} 2>&1 | tee -a "$DEBUGLOG"

# Additional script commands go here

In this script:

  1. We specify the path to the debug log file using the DEBUGLOG variable. Make sure to replace /path/to/debug.log with the actual path and filename where you want to store the log.

  2. 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.

  3. The 2>&1 redirects 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.

  4. The tee command 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 -a option is used with tee to append to the log file if it already exists.

  5. After logging the output, you can continue with the rest of your script logic.

To use this script:

  1. Save the script to a file (e.g., my_script.sh).
  2. Make the script executable by running chmod +x my_script.sh.
  3. 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.

0%