Zsh: stdout and stderr both to console AND log

Abstract: Redirect both stdout and stderr to the terminal and an append-only log file using 2>&1 tee -a in Zsh.

Created: 2026-10-04 by
To redirect both standard output and standard error to the console and a log file in Zsh, use the tee command with process substitution. The pattern command 2>&1 | tee -a logfile captures all output streams, displays them on the terminal, and appends them to the specified file. This approach ensures that debugging information is visible in real-time while preserving a persistent record for later analysis without requiring complex background job management or environment variable hacks.

Understanding File Descriptors

Before implementing redirection, it is essential to understand how shells handle data streams. Every running process in Unix-like systems has three default file descriptors: standard input (fd 0), standard output (fd 1), and standard error (fd 2). By default, both fd 1 and fd 2 point to your terminal emulator. When you run a script, any text printed to stdout appears on the screen, and errors printed to stderr also appear on the screen. To capture these into a file while keeping them visible, you must merge these streams before passing them to a utility like tee. The shell uses specific syntax to manipulate these descriptors. The number 1 represents stdout, and 2 represents stderr. The symbol & allows you to refer to another file descriptor by number rather than a filename. For example, 2>&1 means "redirect file descriptor 2 to wherever file descriptor 1 is currently pointing." This merging step is critical because tee only sees one stream of data; if you do not merge stderr into stdout first, the error messages will bypass tee and go directly to the terminal, leaving the log file incomplete.

The Standard Tee Pattern

The most robust and widely used method for simultaneous logging and console display involves piping the merged output to tee. In Zsh, this is achieved using the pipe operator |. The general structure is:
your_command 2>&1 | tee -a /path/to/logfile.log
Let us break down this command. First, 2>&1 redirects standard error to standard output. At this point, both streams are combined into a single stream flowing through the pipe. Next, tee reads from the pipe. The -a flag tells tee to append to the file rather than overwriting it. If you omit -a, each new execution of the command will erase the previous log contents. Without -a, tee creates a new file or truncates an existing one every time the script runs, which is rarely desired for continuous logging. This pattern works identically in Bash and Zsh. If you are coming from a different shell, note that the order of redirection matters. You must merge stderr to stdout (2>&1) *before* piping to tee. Writing | tee logfile 2>&1 is incorrect because the pipe redirects stdout, but stderr remains separate and goes to the terminal, failing to log errors.

Zsh-Specific Considerations

While the tee pattern is universal, Zsh offers some additional features that can refine this process. One common issue users encounter is interleaved output. If multiple processes write to stdout and stderr simultaneously, their lines may mix up in the terminal. Using stdbuf can help force line buffering, ensuring that tee receives complete lines rather than partial chunks, which makes the log file more readable. However, stdbuf is not always available on all systems, so relying on the core shell redirection is safer for portability. Another consideration is how Zsh handles globbing and aliases. If your command involves complex arguments, ensure that quotes are preserved when passing through the pipe. Generally, simple commands work seamlessly. For more complex scenarios involving functions, you might need to wrap the logic in a function to handle exit codes properly. The exit code of a pipeline is determined by the last command, which is tee. If tee succeeds, the pipeline returns success even if the original command failed. To preserve the original exit status, you can use the PIPESTATUS array in Zsh.
your_command 2>&1 | tee -a logfile.log
exit_code=${PIPESTATUS[0]}
This snippet captures the exit status of your_command before tee completes. This is crucial for scripts that need to react to failures. If you ignore this, your script might continue executing despite the primary command failing, leading to cascading errors.

Handling Background Processes

If you need to run a command in the background while logging its output, the syntax changes slightly. You cannot simply append & at the end of the pipeline, as it would detach tee from the foreground job control. Instead, redirect the entire pipeline to a background job:
(your_command 2>&1 | tee -a logfile.log) &
Wrapping the pipeline in parentheses creates a subshell. The ampersand at the end backgrounds this subshell. This ensures that tee continues to run and write to the file even after the parent shell returns control to the user. Note that the terminal output will still appear, but it may be mixed with subsequent prompts. For production scripts, consider using nohup or proper daemonization tools instead of simple backgrounding to avoid orphaned processes.

Alternative Approaches

Some users prefer using Zsh's built-in print or echo capabilities for custom logging functions. While possible, this adds complexity and overhead compared to the external tee utility. Another alternative is using the exec builtin to permanently redirect file descriptors for the duration of a script.
exec 1>>logfile.log 2>&1
This command redirects stdout to the file and stderr to stdout (which is now the file). Consequently, *all* subsequent output in the script goes to the file, and nothing appears on the console. This is useful for silent installation scripts but fails the requirement of displaying output to the console. Combining exec with tee is possible but often leads to confusing code structures. Stick to the pipe method for clarity and maintainability. For those interested in similar redirection techniques in other contexts, see Redirecting stdout and stderr in Bash: Handling apt-get error output. Additionally, understanding how to handle binary or structured output can be beneficial, as discussed in Redirect ffmpeg showinfo to Pipe with Stderr.

Frequently Asked Questions

Why does my log file miss error messages?

You likely forgot to redirect stderr to stdout before piping to tee. If you write command | tee logfile, only stdout is captured. You must use command 2>&1 | tee logfile to ensure both streams enter the pipe.

How do I prevent tee from overwriting my log file?

Always include the -a (append) flag with tee. Without it, tee treats the file as a new output destination and truncates it upon opening. Use tee -a to add new entries to the end of the existing file.

Can I log to multiple files simultaneously?

Yes, you can chain tee commands. For example, command 2>&1 | tee file1.log | tee file2.log will copy the output to both files. The second tee receives the same stream from the first tee and writes it to the second file while passing it along.

Does this method work in Bash?

Yes, the syntax command 2>&1 | tee -a logfile is POSIX-compliant and works identically in Bash, Zsh, and most other POSIX shells. It is the standard portable solution for dual output.

What happens to the exit code of the command?

The exit code of the pipeline is the exit code of the last command, which is tee. If tee succeeds, the pipeline returns 0, hiding the failure of the original command. Use ${PIPESTATUS[0]} in Zsh or $? immediately after checking the pipeline in Bash to retrieve the original command's exit status.

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