Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Linux/macOS - Shell...
 
Share:
Notifications
Clear all

[Solved] Linux/macOS - Shell - How to Redirect stderr to stdout in Terminal or scripts

1 Posts
1 Users
0 Reactions
2,184 Views
 Hans
(@hans)
Famed Member Admin
Joined: 11 years ago
Posts: 2805
Topic starter  

Terminal/Shell commands can use 3 types of input/output "channels" or I/O streams.
Each stream is represented by a numeric file descriptor:

0 - stdin,  the standard input stream.
1 - stdout, the standard output stream.
2 - stderr, the standard error stream.

(A file descriptor is just a number representing an open file)

The input stream provides information to the program, and the output stream ... well, outputs data haha.
This is where it gets tricky at times though.

Output is done either through the standard output (stdout) or through the "error channel" (stderr).
I refer to these as channels, but that is just to clarify this to those unfamiliar with I/O streams.

Under most circumstances this all works just fine, just sometimes it doesn't when piping output from program/command one to another.

For example:
Normally the standard output is used for piping (passing on) information as an input for another program.
However, sometimes we want the error info instead of the standard output info.

We can however redirect the error channel (stderr) to the standard output channel (stdout) and vice versa.

For example, this will redirect (>) stderr (2) to stdout (1):

2>&1

You can combine this in your sequence of commands.

For example:

somecommand 2>&1 > somefile.txt

The output to the error channel (stderr=2), from somecommand will be redirected (>) to the standard output (1), which then will be redirected (>) to the file somerfile.txt

 

Example for Mac users; hdiutil outputs all its info to stderr. With regular use you won't notice this and everything looks normal.
However, when wanting to redirect the output, the hdiutil output will result in a blank file. Zero output.

This however will output the stderr as regular output:

hdiutil info 2>&1

   
ReplyQuote
Share: