3. Redirections and file operations

Most UNIX shell commands are designed to take plain text input and turn it into plain text output. As we’ve seen so far, by default the output is printed to the terminal. Instead, output can be redirected into a file using > followed by the desired file name:

$ echo "Hello World" > foo

Warning

If a file named foo already exists, it will be replaced by the new output!

To append to a file instead of overwriting it, use >>:

$ echo "Hello World 2" >> foo

Create a file containing a listing of all your directories. (ls has a switch that makes this quite easy.)

cat, less

The content of a file can be printed back directly to the terminal using cat followed by the filename, e.g.:

$ cat foo

Often, especially for long files, less is a better choice. It allows you to move up and down within a file. Type q to exit the program again.

What is the difference between cat foo and echo foo?

mv, cp, rm

Warning

The commands in this section will modify data in existing files. Check carefully for typos!

During the following sequence of operations, check your directory contents with ls after each step, and check the files’ contents with cat. If you’re used to a graphical interface, try to correlate the output of ls with the graphical view of the directory at each step.:

$ cp foo bar
$ mv bar baz
$ rm baz
$ rm bar

What is happening?

Did you notice that commands that work fine usually produce no output. You’ll only get a message if something goes wrong.

file

You may have noticed that files in UNIX do not need to have a three letter extension that identifies the file type (e.g. .txt, .jpg). If they exist, they are simply seen as a part of the file name with no special meaning.

The command file can help in identifying file types. Try it on different files in your home directory:

$ file foo