Piping and Redirecting

kali-linux
Standard input, output, and error streams, redirecting them to files with the redirection operators, and chaining commands with pipes.
Published

Apr 5, 2022

Stream, Piping, and Redirecting

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

Streams in CLI
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 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 us 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
Back to top