Redirecting outputs in UNIX
You can make the output of a command go to a file by using ‘>’
ls > example.dat
This command will copy the result of the ‘ls’ command to the file called example.dat . But this command will overwrite example.dat when you execute it.
You can use ‘>>’ to concatenate the output to an existing file.
echo “This is a header” > example.dat ls >> example.dat
In the above script the ‘echo’ command will create a file, and the ‘ls’ line is going to add to the end of the example.dat.
The other trick is to pipe the output of one command to the input of another one. This way mutiple commands can be chained. The pipe operator is ‘|’. See for example:
du -sk * | sort -nr | head -10
The first command ‘du’ is disk usage. The parameters tell it to make a summary (-s) list in kilobytes (-k) and all files/directories in the current working directory (*). The output is sent to the command ‘sort’ which as the name suggests sorts the text output. We tell it to sort numerically (-n) and in reverse order (-r). Then we use the ‘head’ command to display the first few lines of a text file. In this case we tell it to list 10 lines (-10).