Stream, Piping, and Redirecting
On a Unix-like system, the shell uses streams (a list of characters) for input and output:
| Stream Name | Comment | File Descriptor |
|---|---|---|
| Standard Input (STDIN) | provides input to commands | 0 |
| Standard Input (STDOUT) | displays output from commands | 1 |
| Standard Input (STDERR) | displays error output from commands | 2 |
Redirection
They are used to control the output. If you need to control where your output go, you can add n> or n>>.
n>redirects file descriptionnto a file or device. If the file already exists, it is overwritten and if it does not exist, it will be created.n>>redirects file descriptionnto a file or a device. If the file already exists the stream will be appended to the end of it and if it does not exist, it will be created if the n is not given, the default is standard output.ls 1> listfilesis the same asls > listfilesls 1>> listfilesis the same asls >> listfiles
- The user who runs the command should have write access to the file.
┌──(kaliă‰¿kali)-[~]
└─$ ping -4 -c 3 8.8.8.8 > ping8.txt
┌──(kaliă‰¿kali)-[~]
└─$ cat ping8.txt
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=109 time=22.6 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=109 time=21.6 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=109 time=19.4 ms
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2227ms
rtt min/avg/max/mdev = 19.368/21.188/22.613/1.353 ms
┌──(kaliă‰¿kali)-[~]
└─$ echo "Hello World." > greetings.txt
┌──(kaliă‰¿kali)-[~]
└─$ cat greetings.txt
Hello World.
┌──(kaliă‰¿kali)-[~]
└─$ echo "Mustermann speaking..." >> greetings.txt
┌──(kaliă‰¿kali)-[~]
└─$ cat greetings.txt
Hello World.
Mustermann speaking...
┌──(kaliă‰¿kali)-[~]
└─$ cat /etc/sudoers > sudoers
cat: /etc/sudoers: Permission denied
┌──(kaliă‰¿kali)-[~]
└─$ cat sudoers
┌──(kaliă‰¿kali)-[~]
└─$ cat /etc/sudoers 2> sudoers
┌──(kaliă‰¿kali)-[~]
└─$ cat sudoers
cat: /etc/sudoers: Permission denied
So far, we have learnt how to redirect from stdout to a file. Now, let’s check how we can redirect from a file:
┌──(kaliă‰¿kali)-[~]
└─$ cat < greetings.txt
Hello World.
Mustermann speaking...
┌──(kaliă‰¿kali)-[~]
└─$ wc -m < /etc/resolv.conf
51
┌──(kaliă‰¿kali)-[~]
└─$ wc -l < /etc/resolv.conf
2
Piping
We use the pipe character (|) to redirect the output of the command1 to the input of the command2. Piping different commands together is a powerful tool for manipulating all sorts of data.
┌──(kaliă‰¿kali)-[~]
└─$ cat /etc/resolv.conf | wc -m
51
┌──(kaliă‰¿kali)-[~]
└─$ cat /etc/resolv.conf | wc -l
2