Coding⏱️ 3 min read📅 2026-06-19

How to Fix: How to redirect standard out and standard error to a file, and standard error (only) to console at the same time

Redirect standard output and error to a file while displaying error on console.

Quick Answer: Use the following command: mycommand 2>&1 | tee test.txt; echo $?

The issue described is a common problem faced by users who want to redirect standard output and error streams to a file, while also displaying only the standard error stream in the console. This can be frustrating when trying to troubleshoot or monitor system activity.

This guide aims to provide a step-by-step solution to this issue, explaining the root causes of the problem and offering two primary fix methods.

⚠️ Common Causes

  • The primary cause of this issue is the use of incorrect redirection operators in the command. The `2>&1` operator redirects standard error to the same file as standard output, which can lead to unwanted output being displayed in the console.
  • Another possible cause is the use of outdated or unsupported operating systems or shells, which may not support certain redirection operators.

🔧 Proven Troubleshooting Steps

Using the `tee` Command with Redirectors

  1. Step 1: Open a terminal and navigate to the directory where you want to save the output file.
  2. Step 2: Use the `mycommand` command followed by the redirection operator `2>&1 | tee test.txt`. This will redirect standard output to the same file as standard error, which can lead to unwanted output being displayed in the console.
  3. Step 3: To fix this issue, replace the `2>&1` operator with `2>/dev/null & 1>test.txt`. The `/dev/null` device redirects standard error to /dev/null, effectively discarding it, while `1>test.txt` redirects standard output to the file.

Using Process Substitution

  1. Step 1: Use the `mycommand` command followed by the redirection operator `2>&1 | tee test.txt & mycommand2`. This will redirect standard output to the same file as standard error, while also running another command in the background.
  2. Step 2: To fix this issue, use process substitution to redirect standard output and error streams separately. For example, `mycommand 2>/dev/null & 1>test.txt` redirects standard output to the file, while `mycommand2` runs independently.

🎯 Final Words

By following these steps, you should be able to redirect standard output and error streams to a file, while also displaying only the standard error stream in the console. Remember to test your commands carefully to ensure that they produce the desired output.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions