Unix Power ToolsUnix Power ToolsSearch this book

43.6. Safe I/O Redirection with noclobber

Have you ever destroyed a file accidentally? If you set the noclobber C shell variable or the noclobber option in bash, zsh, and ksh, it can help you avoid these mistakes. Setting noclobber prevents you from destroying a file when you are redirecting standard output (Section 43.1).

Consider the following situation:

% anycommand > outputfile

The command above overwrites the old outputfile. If you have misspelled the name of your output file, or if you have forgotten that the file already exists and contains important data, or (most common) if you really meant to type >> instead of > (i.e., if you really meant to append to the end of outputfile, rather than start a new one), tough luck; your old data is gone.

Setting noclobber prevents this problem. If noclobber is set, the shell will not allow I/O redirection to destroy an existing file, unless you explicitly tell it to by adding an exclamation point (!) after the C shell redirect symbol or by adding a vertical bar (|) in ksh and bash. (The Z shell understands both.) Here are examples. The left column shows csh and tcsh; the right column is for bash (ksh is similar):

% set noclobber              $ set -o noclobber
% ls                         $ ls
filea fileb                  filea fileb
% anyprogram > fileb         $ anyprogram > fileb
fileb: File exists.          bash: fileb: Cannot clobber existing file
% anyprogram >! fileb        $ anyprogram >| fileb
%                            $

Be sure to put space after the !. If you don't, the C shell thinks you're making a history reference and it (usually) prints an error like fileb: Event not found.

Remember that noclobber is not an environment variable, so any new shells you create won't inherit it (Section 35.9). Therefore, if you want this feature, put the set command (above) in your shell's setup file (Section 3.3).

NOTE: In some shells, noclobber will prevent you from redirecting standard output to /dev/null (Section 43.12) or to a terminal unless you add the !.

The noclobber variable has one other feature that's worth noting. Normally, shells let you append to a file that doesn't exist. If noclobber is set under csh, tcsh, and zsh, it won't; you can append only to files that already exist unless you use an exclamation point:

% ls
filea fileb
% anyprogram >> filec
filec: No such file or directory
% anyprogram >>! filec
%

--ML and JP



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.