theshell.ch/site/pages/scripts/8-redirection.html

79 lines
1.7 KiB
HTML
Raw Normal View History

---
layout: page
category-page: scripts
category-title: Scripting
tags: redirect output input
author: Dario Rasic
title: Redirection
previous-page: pages/scripts/7-if.html
---
<h3>output as input</h3>
<br>
To redirect a certain output of the command-line we have to use the symbol "&gt;".<br>
In this case, we will use a file named <i>hello.txt</i>, in which we want to insert
a certain output ("Sun" in this case):<br>
<pre>
echo "Sun" &gt; hello.txt
</pre>
So if we print the content of the file in our command-line, the output will be the following:
<pre>
cat hello.txt
Sun
</pre>
If we want to append a certain output to an existing file,
we just have to use "&gt;&gt;" symbols:
<pre>
cat hello.txt
Sun
echo "Moon" &gt;&gt; hello.txt
cat hello.txt
Sun
Moon
</pre>
<!-- Input redirection text -->
<h3>input as output</h3>
<br>
To redirect an input from a file for a command, the symbol "&lt;" is used.
<pre>
echo $lt; $(cat hello.txt)
Sun
Moon
</pre>
This is particularly useful when chaining commands.<br>
<!-- Chaining command text -->
<h3>Chaining (or piping)</h3>
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.
<pre>
cat hello.txt | grep Mo
Moon
</pre>
<h3>A simple example</h3>
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>
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 &lt; animals.txt &gt; d_animals.txt
cat d_animals.txt
Deer
Dog
Dolphin
...
</pre>