A little adventure with STDIN, STDOUT and STDERR in linux

Published by moxlotus on

Recently, a colleague was showing me some output from a program that is executed in linux environment. So he asked me why he is not able to remove these output from the console even though he has used the linux redirect for the program output on the terminal. The command below is how you can redirect the output from a program to a file named output.txt

./myprogram > output.txt

Long before this, I have learned about STDIN, STDERR, STDIN from the book "The Linux Command Line". So I told him that it is probably because somewhere in the source code exists some lines of codes that actually prints to the STDERR instead of STDIN. In order to solve this issue, we have to redirect not just the STDIN, also the STDERR. To achieve that we have to first redirect STDERR to STDIN. So how do we do that? In fact, the STDIN, STDOUT and STDERR are being assigned a file descriptor number which are 0, 1 and 2 respectively. With that in mind, below is an example of how one can achieve it.

./myprogram > output.txt 2>&1

So at the back of our command, we will have to indicate we want STDERR, which is 2, to be be redirected to the STDIN which is represented by the file descriptor number 1. And an alternative and shorter form of the above command is

./myprogram &> output.txt

Just in case that you are curious about where to locate these file descriptors under your system, they can be found under the /dev/fd directory.

Share it with others
Categories: Linux


Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *