Redirecting I/O

Redirecting Output

We use the > symbol to redirect the output of a command. For example, to create a file called menu containing a list of meals, type

$HOME $> cat > menu

Then type in the names of some fruit. Press Return after each one.

orange
soup
cake
^D (Control D to stop)

What happens is the cat command reads the standard input (the keyboard) and the redirects the output, which normally goes to the screen, into a file called menu

To read the contents of the file, type

$HOME $> cat menu

Exercise

Using the above method, create another file called fruits containing the following fruit: melon, plum, mango, grapefruit. Read the contents of fruits 

The form >> appends standard output to a file. So to add more items to the file list1, type

$HOME $> cat >> menu

Then type in the names of more meals

meat
fish
bread
^D (Control D to stop)

To read the contents of the file, type

$HOME $> cat menu

You should now have two files. One contains six fruit, the other contains four fruit. We will now use the cat command to join (concatenate) list1 and list2 into a new file called biglist. Type

$HOME $> cat menu fruits > shopping_list

What this is doing is reading the contents of list1 and list2 in turn, then outputting the text to the file shopping_list

To read the contents of the new file, type

$HOME $> cat shopping_list

Redirecting Input

We use the < symbol to redirect the input of a command.

The command sort alphabetically or numerically sorts a list. Type

$HOME $> sort

Then type in the names of some vegetables. Press Return after each one.

carrot
turnip
broccoli
^D (Control d to stop)

The output will be

broccoli
carrot
turnip

Using < you can redirect the input to come from a file rather than the keyboard. For example, to sort the list of fruit, type

$HOME $> sort < shopping_list

and the sorted list will be output to the screen. To output the sorted list to a file, type,

$HOME $> sort < shopping_list > ordered_list

Use cat to read the contents of the file slist

Supported By

File Browser Reference
Department FHERIS
University of Galway
HEA Logo