Redirection
There is another category of Input and Output when dealing with file input and output, and that is redirection. There is an implicit fluid metaphor in the Unix structure, as the flow of data through pipelines and arrowed brackets. Data flows from left to right through a pipe, and also in the direction of the arrow. Multiple arrows indicate appending instead of overwriting (or creating).
Redirecting Output: The Single Greater-Than Arrow (>)
The single-arrowed command > filename structure creates filename if it does not already exist. If filename does already exist, it is truncated to zero length, but its inode details remain as before. This structure is useful for writing to log files, creating data files, and performing most general file create-and-open tasks. If the file cannot be written to, the whole command line fails, and none of it is executed at all. The simple script that follows shows the file being created if it does not already exist, and truncated if it does exist. The date command shows that different data has been written to the file on the second time, but the original content has disappeared.
Although the file permissions are unchanged if the file already existed, if the file did not exist, it will be created with the standard permissions and ownership as dictated by the current value of umask (2).
$ cat create.sh #!/bin/bash LOGFILE=/tmp/log.txt ...
Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.