3.2 Redirect



3.2.1 Redirect output

In the case of "output to standard output" described in the previous section, this output means the output destination of the shell. With the shell on UNIX, you can change the output destination to a file etc. That is called redirect. This redirect can be used by the symbol '>'. You can enter the following.

Example

$ ls > ls-output ↵


You can find a file named "ls-output" is created. Check the contents of the file "ls-output" with the cat command. It contains the same contents as when ls was executed. By using redirect like this, you can change the output destination and store the output in the file.

Practice: Redirect to a file


Let's output the result of ls to ls-output, actually.

$ ls > ls-output ↵
$ cat ls-output ↵            Display the contents of ls-output


The file named "ls-output" is generated, saved the result of "ls". If the file "ls-output" exist, the old file is deleted and the new file is generated. If you want to add its output to the file "ls-output", you should use ">>" instead of ">".

3.2.2 File creation by cat command

In previous section, we created a file by redirecting the standard output. By combining cat command and redirect, you can create files which has contents you like.

Practice: File creation by cat command


$ cat > cat-output ↵
Hello ↵
This is cat redirect. ↵
(Enter Control-d)
$


Control-d is the key which means EOF (End of File), and it means the end of input data. In UNIX, when reading EOF, the input is ended. The cat command judge as the end of data by receive the EOF(Controld), then terminate the redirection.

There is also the key bind such as Control-c. It is called as interrupt, has the function to interrupt a process. For example, when you want to stop a program because it does not work properly, you can stop a program by entering Control-c.


Column: cat is "concatenate"?


The cat command has so far been used with the function of "displaying the contents of a file" in many cases. cat has its original word like ls has LiSt. That is conCATenate (connection).

You may feel some gaps between displaying and concatenating. In this case, if you add words 'to standard output' to the word 'concatenate', you may feel more comfortable. i.e. 'cat FILE' means 'concatenate FILE to standard output'.



Previous Next