I/O redirection in Linux explained with examples

Spread the love

So far we learned how to run commands in the command line and received a stream of output in the terminal. In this post, we’ll focus on input and output (I/O) redirection.

Through redirection you can direct the input and output of a command to and from other files and programs, and chain commands together in a pipeline.

>

cat brad_pitt.txt > dwayne_johnson.txt

> takes the standard output of the command on the left, and redirects it to the file on the right. Here the standard output of cat brad_pitt.txt is redirected to dwayne_johnson.txt.

Note that > overwrites all original content in dwayne_johnson.txt. When you view the output data by using cat on dwayne_johnson.txt, you will see only the contents of brad_pitt.txt.

>>

Now we know how to overwrite a file’s contents, but what if we want to be able to add to a file without losing the original text? We can use the >> command!

cat brad_pitt.txt >> dwayne_johnson.txt

>> takes the standard output of the command on the left and appends (adds) it to the file on the right.

Here, the output data of dwayne_johnson.txt will contain the original contents of dwayne_johnson.txt with the content of brad_pitt.txt appended to it.

<

cat < tom_hanks.txt

< takes the standard input from the file on the right and inputs it into the program on the left. Here, tom_hanks.txt is the standard input for the cat command. The standard output appears in the terminal.

|

| is a “pipe.” The | takes the standard output of the command on the left, and pipes it as standard input to the command on the right. You can think of this as “command to command” redirection.

cat tom_hanks.txt | wc 

Above, the output of cat tom_hanks.txt becomes the standard input of wc. In turn, the wc, “word count”, command outputs the number of lines, words, and characters in tom_hanks.txt, respectively.

cat tom_hanks.txt | wc | cat > julia_roberts.txt

Multiple |s can be chained together. Here the standard output of cat tom_hanks.txt is “piped” to the wc command. The standard output of wc is then “piped” to cat. Finally, the standard output of cat is redirected to julia_roberts.txt.

We can view the output data of this chain by typing cat julia_roberts.txt.

sort

sort actors.txt

sort takes the standard input and orders it alphabetically for the standard output (it doesn’t change the file itself). Here, the continents in actors.txt will be listed in alphabetical order:

cat actors.txt | sort > sorted_actors.txt

Here, the command takes the standard output from cat actors.txt and “pipes” it to sort. The standard output of sort is redirected to a new file named sorted_actors.txt.

Rating: 1 out of 5.

Leave a Reply