LKBEN11022: Howto use pipes and redirections in a linux bash shell


This article has not been checked!

LKB | Created: 02/04/2020 | Version: 0 | Language: EN | Rating: 0 | Outdated: False | Marked for deletion: False

Author: Wim Peeters - Keskon GmbH & Co. KG


Symptom

You need to pipe results in a file are into another command

Cause

none

Solution


First you need to know a few things about input and output. There are tree channels per default.

stdin  : which stands for standard in
stdout : standard out
stderr : standard error

Then we have the following operators

normal pipe > out

Please note that a set -o noclobber can produce errors on overwrite attempts!

normal pipe < in

here documents << (see also the knowledge base article about here documents)

normal error 2>

The normal pipe command |

Here a few examples:

Here we search alle files with myname<wildcard> from the root and pipe them in a file out1.txt, the errors go to the file errors.txt.

find / -iname 'myname*' > out1.txt 2> errors.txt

This will do the same but the errors are appended to the out1.txt file.

find / -iname 'myname*' > out1.txt 2>$1

Now we would like to sort the output of the first command and prepare it for printing by writing a file sortedlist.txt.

find /i -iname 'myname*' | sort | pr -2 > sortedlist.txt

There are much more possibilities in using piping and redirection. Please note that not all command use stdin, stdout and stderr, use the help of the command for more information.

About the Author

Wim Peeters is electronics engineer with an additional master in IT and over 30 years of experience including time spent in support, development, consulting, training and database administration. Wim has worked with SQL Server since version 6.5. He has developed in C/C++, Java and C# on Windows and Linux in different European countries and different European languages. He writes knowledge base articles to solve IT problems and publishes them on the Lubby Knowledge Platform where he is one of the most important contributors and the main developer.

Disclaimer:

The information provided in this document is intended for your information only. Lubby makes no claims to the validity of this information. Use of this information is at own risk!