loader

Stream, Piping, and Redirecting

On a Unix-like system, the shell uses streams (a list of characters) for input and output:

Stream NameCommentFile Descriptor
Standard Input (STDIN)provides input to commands0
Standard Input (STDOUT)displays output from commands1
Standard Input (STDERR)displays error output from commands2
Streams in CLI

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 description n to 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 description n to 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> listfiles is the same as ls > listfiles
    • ls 1>> listfiles is the same as ls >> 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

Leave a Reply

Your email address will not be published. Required fields are marked *