.. highlight:: console .. role:: bash(code) :language: bash :class: highlight Redirections and file operations -------------------------------- .. %No file extension required 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 :dfn:`redirected` into a file using :bash:`>` followed by the desired file name:: $ echo "Hello World" > foo .. warning:: If a file named :file:`foo` already exists, it will be replaced by the new output! To append to a file instead of overwriting it, use :bash:`>>`:: $ echo "Hello World 2" >> foo Create a file containing a listing of *all* your directories. (:command:`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 :command:`cat` followed by the filename, e.g.:: $ cat foo Often, especially for long files, :command:`less` is a better choice. It allows you to move up and down within a file. Type :kbd:`q` to exit the program again. What is the difference between :bash:`cat foo` and :bash:`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 :command:`ls` after each step, and check the files' contents with :command:`cat`. If you're used to a graphical interface, try to correlate the output of :command:`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. .. \footnote{One of the reasons for this was to save paper in the teletype.} 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. :kbd:`.txt`, :kbd:`.jpg`). If they exist, they are simply seen as a part of the file name with no special meaning. The command :command:`file` can help in identifying file types. Try it on different files in your home directory:: $ file foo