Suppose you run a command, say route
, and want to save the output in a file. The redirection (>
) operator is used to do this instead of sending the output to the screen.
Let's try some redirection:
Enter
ifconfig > file1.txt
. You won't see anything, because the output went into the file.Run
cat file1.txt
. You should now see the output.This works the other direction as well, to read from a file run the following command:
sort < file1.txt
You can even do both in one step:
sort < file1.txt > output-file.txt
You can also send the output to another command using the pipe operator. For example, run
route | grep eth0
. The above command would display only the lines fromroute
that contain the phraseeth0
.
Here is something that I use all the time. Say I have written a program in C a long time ago, have several versions, and want to find the latest one. I could run locate
to find them all:
locate crc.c
This might return quite a few lines. How can I run ls
on each file to find the latest one? By piping the output into the xargs
command and then ls
:
locate crc.c | xargs ls -la
This will now show the time and date of each file.
This might seem a bit complicated at first, but if you experiment a little it will become second nature to you.