Skip to content

Redirections#

So we've piped the output (stdout) of one command into the input (stdin) of another. Now we're going to use redirects to do a few different things.

First we're going to use our cat | wc example from earlier to change where wc's stdout goes. Let's do that now:

1
2
3
michael@develop:~$ cat helloworld.txt | wc -w > helloworld.txt.count
michael@develop:~$ cat helloworld.txt.count
2

Note

I use the -w flag so that I only get words in the output.

I used the > redirection to write the stdout of wc -w to a regular file on the file system. Whatever is on the right side of the > is opened as a file for writing to. If the file exists, it is overwritten and everything already existing inside the file is deleted. Consider yourself warned!

We're using the cat command and a | to get the contents of a file from the filesystem and into the stdin of wc. Let's use the other read < redirect to remove the for using cat:

1
2
michael@develop:~$ wc -w < helloworld.txt
2

Now I just get 2 to my stdout because I didn't use | or > to pipe or redirect the stdout anywhere, so it went to my display.

What we did here was use the < redirect to read from the file on the right handside. Anything on the right of the < is opened for read (only) and the contents are never overwritten. What's read from the file is then fed into the stdin of the command on the left of the redirect.

Now let's combine the two!

1
2
3
michael@develop:~$ wc -w < helloworld.txt > helloworld.txt.count
michael@develop:~$ cat helloworld.txt.count
2

Now we've used the < redirect to read the file on the right of it, then used when wc has finished working and write to its stdout, that's passed to our > redirect which then writes the contents of stdout to the file to its right, which it opened for writing.

There is more to redirecting, but that's the basics for now.