2018-11-10 21:05:37 +00:00
---
layout: page
category-page: scripts
category-title: Scripting
2018-11-11 12:33:39 +00:00
tags: redirect output input
2018-11-10 21:05:37 +00:00
author: Dario Rasic
title: Redirection
---
2018-11-12 10:47:50 +00:00
< p >
2018-11-10 21:05:37 +00:00
2018-11-14 10:55:05 +00:00
< h3 > output as input< / h3 >
2018-11-12 19:14:49 +00:00
< br >
To redirect a certain output of the command-line we have to use the symbol "> ".< br >
2018-11-10 21:05:37 +00:00
2018-11-12 10:47:50 +00:00
In this case, we will use a file named < i > hello.txt< / i > , in which we want to insert
2018-11-10 21:05:37 +00:00
a certain output ("Sun" in this case):< br >
< pre >
echo "Sun" > hello.txt
< / pre >
So if we print the content of the file in our command-line, the output will be the following:
2018-11-12 10:47:50 +00:00
2018-11-10 21:05:37 +00:00
< pre >
cat hello.txt
2018-11-12 10:47:50 +00:00
Sun
2018-11-10 21:05:37 +00:00
< / pre >
If we want to append a certain output to an existing file,
2018-11-12 19:14:49 +00:00
we just have to use "> > " symbols:
2018-11-10 21:05:37 +00:00
< pre >
cat hello.txt
2018-11-12 10:47:50 +00:00
Sun
2018-11-10 21:05:37 +00:00
echo "Moon" >> hello.txt
cat hello.txt
2018-11-12 10:47:50 +00:00
Sun
Moon
2018-11-10 21:05:37 +00:00
< / pre >
2018-11-11 12:33:39 +00:00
<!-- Input redirection text -->
2018-11-14 10:55:05 +00:00
< h3 > input as output< / h3 >
2018-11-12 19:14:49 +00:00
< br >
2018-11-10 21:05:37 +00:00
To redirect an input from a file for a command, the symbol "< " is used.
< pre >
echo < $(cat hello.txt)
2018-11-12 10:47:50 +00:00
Sun
Moon
2018-11-10 21:05:37 +00:00
< / pre >
2018-11-12 19:14:49 +00:00
< p > This is particularly useful when chaining commands.< / p >
< br >
<!-- Chaining command text -->
2018-11-14 10:55:05 +00:00
< h3 > chaining (or piping)< / h3 >
2018-11-12 19:14:49 +00:00
< br >
Chaining, also called Piping because it works with the pipe symbol "|", takes the output of a certain command-line and feeds it to another command in a direct way.
<!-- Table for the example of the piping command -->
< pre >
cat hello.txt | grep Mo
Moon
< / pre >
2018-11-10 21:05:37 +00:00
2018-11-12 19:14:49 +00:00
<!-- A simple example -->
2018-11-14 10:55:05 +00:00
< h3 > simple example< / h3 >
2018-11-11 12:33:39 +00:00
< br >
2018-11-12 19:14:49 +00:00
Now let's say that we want to combine those commands in a more complex operation. Let's say we want to take some contents from a certain file and put it into another file.< br >
2018-11-10 21:05:37 +00:00
2018-11-12 19:14:49 +00:00
We want to sort the animals whose name begins with letter "d" from the file < i > animals.txt< / i > and put it into < i > d_animals.txt< / i > .< br >
< pre >
grep d < animals.txt > d_animals.txt
2018-11-11 12:33:39 +00:00
< br >
2018-11-12 19:14:49 +00:00
cat d_animals.txt
Deer
Dog
Dolphin
...
< / pre >
2018-11-10 21:05:37 +00:00
< / p >