Bash: Achieving Side Output - An Easy Way?

Abstract: Use tee to display command output on the terminal while simultaneously saving it to a file for logging.

Created: 2026-09-17 by

Side output in Bash allows you to display information on the terminal while simultaneously saving it to a file. The most common and robust method is using the tee command, which reads from standard input and writes to both standard output and one or more files. This technique is essential for logging script progress without losing real-time feedback.

Understanding Standard Streams

To master side output, you must first understand how Bash handles data streams. Every process has three default streams: standard input (stdin), standard output (stdout), and standard error (stderr). By default, stdout points to your terminal screen, allowing you to see command results as they happen. Redirect operators like > change where stdout goes, typically sending it to a file instead of the screen. However, this redirection hides the output from the user entirely, which is often undesirable during long-running scripts.

Side output solves this by splitting the stream. It ensures that the data remains visible on the console while also being captured for later review. This dual behavior is particularly useful when debugging complex pipelines or monitoring system processes that run for extended periods. Without this capability, you would either have to sacrifice visibility for persistence or vice versa.

The Primary Solution: Using tee

The tee utility is the standard tool for achieving side output. It takes input from stdin and copies it to both stdout and the specified file(s). The name comes from the T-splitter used in plumbing, which accurately describes its function in data processing. When you pipe a command into tee, the output continues down the pipeline to any subsequent commands, while a copy is written to disk.

command | tee output.log

In this example, command runs normally, and its output appears on your screen. Simultaneously, output.log is created (or overwritten) with the exact same content. If you want to append to an existing log file rather than overwriting it, use the -a flag:

command | tee -a output.log

This approach is non-destructive and safe for iterative testing. It works seamlessly with other Unix utilities, maintaining the flow of data through pipes. You can chain multiple tee commands if you need to save logs to different locations based on specific criteria, though simple piping is usually sufficient for most scripting needs.

Capturing Both Standard Output and Error

Often, scripts produce errors alongside normal messages. By default, stderr bypasses the pipe and goes directly to the terminal. To capture both streams in your side output file, you must redirect stderr to stdout before piping to tee. This is done using the 2>&1 syntax, which tells Bash to send file descriptor 2 (error) to file descriptor 1 (standard output).

command 2>&1 | tee output.log

This ensures that warning messages and stack traces are included in your log file while still appearing on the screen. It provides a complete picture of the script's execution environment. Without this step, your log file might appear empty or incomplete even if the script failed critically.

Alternative Methods and Considerations

While tee is the most elegant solution, other methods exist depending on your specific constraints. One alternative is using process substitution or subshells to redirect output manually. For instance, you can wrap a command group in parentheses and redirect the entire block’s output to a file while letting individual commands print to the terminal. However, this approach is less flexible for streaming data and harder to maintain in complex scripts.

Another consideration is performance. For very large outputs, tee introduces minimal overhead because it simply duplicates the byte stream. However, if you are dealing with massive binary files, ensure your filesystem has enough space and I/O bandwidth. As noted in previous troubleshooting guides, issues often arise from quoting problems or unexpected file permissions rather than the tee mechanism itself.

For scenarios where you only need to log and not interact with the output further, direct redirection with >> inside the script loop is an option. But this requires manual management of file descriptors and breaks the clean separation of concerns that tee provides. It is generally recommended to stick to tee for clarity and reliability.

Practical Examples in Scripting

Consider a backup script that compresses a directory. You want to see which files are being processed in real-time but also keep a record of what was backed up. Using tar with tee achieves this perfectly:

tar czf backup.tar.gz /data 2>&1 | tee backup.log

This single line handles compression, logging, and visibility. If the backup fails, the log file contains the error message, aiding in diagnosis. This pattern is reusable across many administrative tasks, from deploying code to running database migrations.

Additionally, you can combine side output with conditional logic. If you only want to log errors, you can filter the output using grep before passing it to tee. This keeps your logs clean and focused on actionable items. Remember that filtering happens after the command runs, so the original command still sees all output unless you modify its internal behavior.

For more advanced date handling in these logs, consider integrating time stamps. Tools like those discussed in our guide on date-time conversion can help format log entries consistently. Proper formatting makes it easier to parse logs later using automated tools or grep searches.

Troubleshooting Common Issues

If your side output does not appear as expected, check two main areas: permissions and buffering. Ensure the user running the script has write access to the target file. Also, note that some commands buffer their output when not connected to a terminal. In such cases, tee might delay displaying output until the buffer fills. Using --line-buffered with tee can force immediate display of each line, improving interactivity.

Another common pitfall is misunderstanding how pipes work. If you place tee incorrectly in the pipeline, you might lose data or create circular dependencies. Always verify the direction of data flow. Referencing resources on preventing script interruptions can also help if your logs seem to stop abruptly due to signal handling.

Frequently Asked Questions

Does tee corrupt binary data?

No, tee handles binary data correctly and does not corrupt null bytes or special characters. It operates at the byte level, making it safe for copying executables, images, or compressed archives just as it is for text logs.

How do I timestamp every line in my log?

You can pipe the output of tee into a loop or use ts from the moreutils package. Alternatively, wrap your command to prepend timestamps manually, ensuring each line gets a unique identifier for chronological sorting.

Can I split output to multiple files at once?

Yes, tee accepts multiple filenames. For example, command | tee file1.txt file2.txt will write identical content to both files while still displaying it on the screen. This is useful for separating logs by severity or component.

Why is my output delayed when using tee?

This is usually due to output buffering. Commands often buffer output when writing to pipes instead of terminals. Adding --line-buffered to your tee command forces it to flush after every newline, providing real-time updates.

Is there a way to log only errors?

You can filter the stream using grep before tee, such as command 2>&1 | grep -i error | tee error.log. This ensures only lines containing "error" are saved and displayed, keeping other logs separate.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More