Skip to content

Redirecting Output

Redirection Operators

Now that you know how to run a few basic commands and programs, it is a good time to teach you how we can redirect their output. The default behaviour is to display their output to the standard output stdout so that we can see it. However, we are also able to redirect the output to a file. To do this we use the > operator followed by the file we want to store the output in. Note, the echo command just outputs what you put in to it.

Text Only
% echo "Wow! This guide has been super helpful for me :)" > tootrue.txt

% cat tootrue.txt
Wow! This guide has been super helpful for me :)

Another operator is >>. This operator will append the output to a file. That is, if it already exists! If it doesn't, then it beahves the the same as >, which overwrites/creates instead of appends.

Text Only
% echo "I agree!" >> tootrue.txt

% cat tootrue.txt
Wow! This guide has been super helpful for me :)
I agree!

The last kind of redirect operator is the pipe | operator, which redirects the output between programs/commands.

Text Only
% ls -l /
total 108
drwxr-xr-x   2 root root  4096 Sep 11 06:37 bin
drwxr-xr-x   4 root root  4096 Sep 19 06:59 boot
drwxr-xr-x  19 root root  4000 Sep  4 15:07 dev
drwxr-xr-x 186 root root 12288 Sep 19 06:56 etc
drwxr-xr-x  43 root root  4096 Sep  4 15:33 home
lrwxrwxrwx   1 root root    33 Sep 19 06:58 initrd.img -> boot/initrd.img-4.15.0-64-generic
lrwxrwxrwx   1 root root    33 Sep 19 06:58 initrd.img.old -> boot/initrd.img-4.15.0-62-generic
drwxr-xr-x  25 root root  4096 Sep  4 16:09 lib
drwxr-xr-x   2 root root  4096 Sep  4 16:09 lib32
drwxr-xr-x   2 root root  4096 Jul 25  2018 lib64
drwx------   2 root root 16384 Sep  4 13:21 lost+found
drwxr-xr-x   2 root root  4096 Jul 25  2018 media
drwxr-xr-x   2 root root  4096 Jul 25  2018 mnt
drwxr-xr-x   6 root root  4096 Sep 18 16:47 opt
dr-xr-xr-x 259 root root     0 Sep  4 14:13 proc
drwx------   5 root root  4096 Sep 10 15:55 root
drwxr-xr-x  41 root root  2420 Sep 19 15:14 run
drwxr-xr-x   2 root root 12288 Sep 19 06:56 sbin
drwxr-xr-x   4 root root  4096 Sep  4 13:28 snap
drwxr-xr-x   2 root root  4096 Jul 25  2018 srv
dr-xr-xr-x  13 root root     0 Sep  4 20:10 sys
drwxrwxrwt  80 root root 12288 Sep 19 15:09 tmp
drwxr-xr-x  12 root root  4096 Sep  4 16:09 usr
drwxr-xr-x  19 root root  4096 Sep  4 15:05 var
lrwxrwxrwx   1 root root    30 Sep 19 06:58 vmlinuz -> boot/vmlinuz-4.15.0-64-generic
lrwxrwxrwx   1 root root    30 Sep 19 06:58 vmlinuz.old -> boot/vmlinuz-4.15.0-62-generic

% ls -l / | grep lib
drwxr-xr-x  25 root root  4096 Sep  4 16:09 lib
drwxr-xr-x   2 root root  4096 Sep  4 16:09 lib32
drwxr-xr-x   2 root root  4096 Jul 25  2018 lib64

Here, we redirected the output of the ls command into the grep command, where grep restricts the output only to lines that contain the given pattern, in this case "lib".