More About Redirections

We have already introduced and used the basic I/O redirection operators: <, >, >>, and |. In this section, we look at the rest of the available operators and examine the fundamentally important issue of file-descriptor manipulation.

Additional Redirection Operators

Here are the additional operators that the shell provides:

Use >| with set -C

The POSIX shell has an option that prevents accidental file truncation. Executing the command set -C enables the shell's so-called noclobber option. When it's enabled, redirections with plain > to preexisting files fail. The >| operator overrides the noclobber option.

Provide inline input with << and <<-

Use program << delimiter to provide input data within the body of a shell script.

Such data is termed a here document. By default, the shell does variable, command, and arithmetic substitutions on the body of the here document:

cd /home            Move to top of home directories
du -s *      |      Generate raw disk usage
  sort -nr   |      Sort numerically, highest numbers first
    sed 10q  |      Stop after first 10 lines
      while read amount name
      do
          mail -s "disk usage warning" $name << EOF
Greetings. You are one of the top 10 consumers of disk space
on the system.  Your home directory uses $amount disk blocks.

Please clean up unneeded files, as soon as possible.

Thanks,

Your friendly neighborhood system administrator.
EOF
      done

This example sends email to the top ten "disk hogs" on the system, asking them to clean up their home directories. (In our experience, ...

Get Classic Shell Scripting 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.