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-12 19:14:49 +00:00
< h3 > Output as input< / h3 >
< 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-12 10:47:50 +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 -->
< h3 > Chaining (or Piping)< / h3 >
< 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 -->
< 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 >