You type a command, run it, it finishes without a single error, and the file is empty. No trash can, no warning, no undo. It has happened to almost everyone who works in a terminal, and the culprit is a single character: >.
The shell has had an option for decades that turns that silent disaster into a clear error message. It’s called noclobber, it takes one line to enable, and hardly anyone knows about it. This article explains why the problem happens, how the protection works under the hood, where it falls short and what to do when you really do want to change a file in place.
Everything below was tested on Debian 13 with GNU bash 5.2.37, with comparisons against zsh 5.9, dash 0.5.12 and fish 4.0.2 from the same distribution.
What “clobber” means
To clobber something is to smash it. In Unix jargon it means overwriting a file and losing what was in it. That is exactly what > does: if the file exists, it truncates it to zero and writes over it. It doesn’t ask.
Often that’s what you want: a report you regenerate, a fresh log on every run. The trouble starts when the file held something you needed, or when you type > where you meant >>. An echo "10.0.0.5 db" > /etc/hosts instead of >> leaves the file with a single line, and you find out when localhost stops resolving.
The trap of reading and writing the same file
The classic case is sorting a file and saving the result into itself:
$ printf "carol\nalice\nbob\n" > names.txt
$ sort names.txt > names.txt
$ wc -c names.txt
0 names.txt
Zero bytes. sort didn’t fail or say anything; there was simply nothing left to sort. The reason is the order in which the shell does things: it sets up redirections first and only then starts the program. strace shows it clearly:
openat(AT_FDCWD, "names.txt", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
That O_TRUNC empties the file the moment it’s opened, before sort even exists. When sort starts and opens names.txt to read it, it’s already empty. The damage was done before the command began.
Any command that reads and writes the same file on one line falls into the same hole:
grep alice names.txt > names.txt
head -2 names.txt > names.txt
sed 's/alice/alicia/' names.txt > names.txt
cat names.txt | tr a-z A-Z > names.txt
The pipe in the last example saves nothing: both sides start at the same time and the final redirection is applied before cat has read a byte. With large files it sometimes looks like it works, because cat manages to read a chunk first. That’s a race, and the result changes from one run to the next.
Turning noclobber on
set -o noclobber
Or the short form, which is the one POSIX defines:
set -C
It prints nothing. To check it’s active:
$ set -o | grep noclobber
noclobber on
It also shows up as a C in $-, the variable holding the letters of the active options (echo $- prints something like himBCHs), which is the handiest way to check from inside a script. With it on, repeat the mistake:
$ sort names.txt > names.txt
bash: names.txt: cannot overwrite existing file
$ echo $?
1
$ cat names.txt
carol
alice
bob
The shell refuses to open the file, sort never runs and the command returns 1. The contents are untouched. To switch it off again, set +o noclobber or set +C.
How it works inside
Bash doesn’t just check “does it exist?” and then open the file. That would leave a window between the check and the write. With noclobber on, the same strace changes:
newfstatat(AT_FDCWD, "nuevo2.txt", ...) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "nuevo2.txt", O_WRONLY|O_CREAT|O_EXCL, 0666) = 3
newfstatat(AT_FDCWD, "f.txt", {st_mode=S_IFREG|0644, st_size=2, ...}, 0) = 0
For a new file it uses O_CREAT|O_EXCL instead of O_TRUNC. According to the open(2) man page, that combination guarantees the call fails if the file already exists, and the check and creation are a single kernel operation. If two processes try at once, only one wins. For the existing file (f.txt), bash sees with stat that it’s a regular file and doesn’t even try to open it. That detail is what makes the lock trick further down possible.
Overwriting on purpose: >|
Sometimes you do want to replace the file. With noclobber on, the way to say so is >|:
echo "new content" >| report.txt
The extra bar is a statement of intent. To destroy data you have to type something deliberate, and that extra second is what prevents accidents. >| is in the POSIX standard, so it works the same in bash, dash, ksh and zsh.
Creating a file that doesn’t exist needs nothing special: echo hello > new.txt works as usual. noclobber only protects what’s already there.
What it protects and what it doesn’t
This is the part worth memorising, because trusting noclobber too much is another way to get burned. Here’s what the test showed in bash 5.2:
| Operation | Blocked by noclobber? |
|---|---|
command > file |
Yes |
command &> file and command > file 2>&1 |
Yes |
exec 3> file |
Yes |
> file on an empty file that already exists |
Yes, that too |
> link when the symlink points to something that doesn’t exist |
Yes (O_EXCL fails) |
command >> file |
No, it appends and deletes nothing |
command > /dev/null and other special files |
No, it only guards regular files |
command 1<> file |
No, and it writes over the first bytes |
tee, cp, mv, sed -i, dd, truncate, rsync |
No, they’re programs, not redirections |
Two cases deserve a comment. The first is <>, which opens a file for reading and writing without truncating it. noclobber doesn’t treat it as an overwrite, but the result can be just as bad:
$ echo hola 1<> names.txt
$ cat names.txt
hola
alice
bob
dave
The five bytes of hola\n have stomped on carol\n, leaving a blank line behind. It’s rarely used, but worth knowing about.
The second is that noclobber is a shell option. tee file, cp, mv and sed -i open files themselves and never consult it. command | tee report.txt wipes report.txt even with noclobber on.
Finally, the option is inherited by subshells (( ... ), $( ... ) substitutions), but not by scripts you run: bash script.sh starts a fresh non-interactive shell that doesn’t read your ~/.bashrc. In the test, the same echo z > names.txt the interactive shell blocked ran without complaint from a script.
Making it permanent
An option typed in the terminal disappears when you close it. To keep it, add the line to ~/.bashrc:
echo 'set -o noclobber' >> ~/.bashrc
source ~/.bashrc
(Note the >>. With noclobber on, a > here would have failed; without it, it would have left your .bashrc with a single line.)
~/.bashrc is the right place because only interactive shells read it, the ones you type commands into. System scripts, installers and packages expect to overwrite files with >, and forcing noclobber on all of them would break things. So:
- Don’t put it in
/etc/profileor/etc/bash.bashrcunless you want to affect every user on the machine. - Don’t export it through
SHELLOPTS. Bash passes the options listed in that variable to its children if it’s exported. In the test, withexport SHELLOPTS, an ordinary script inherited noclobber and failed to write its file. - On Debian and Ubuntu, keep it after the interactivity check in the default
.bashrc(case $- in *i*) ;; *) return;; esac). Bash also reads.bashrcwhen a remote command runs over SSH, and that check keeps it out of those cases. Appending it to the end of the file, as above, does the job. - If you often work as root, add it to
/root/.bashrctoo. That’s where a careless>does the most damage.
To start a single protected shell without touching anything, there’s bash -C.
noclobber in your own scripts
In a script of your own it can make sense to turn it on at the top and use >| only where rewriting is intended. Be clear about how it fails: the redirection isn’t opened, the command never runs and the exit status is 1. If the script uses set -e, it stops right there, which is usually what you want:
#!/bin/bash
set -euo pipefail
set -o noclobber
report="/var/tmp/report-$(date +%F).txt"
generate_report > "$report" # fails if today's already exists
summary >| /var/tmp/latest.txt # this one is always rewritten, on purpose
Without set -e, the failure slips by and the script carries on. Check the result with || { echo "$report already exists" >&2; exit 1; } if you don’t use set -e.
Safe ways to change a file in place
noclobber blocks the broken pattern, but the original problem is still there: you want to sort the file and keep the result. These are the options, with their fine print.
1. The program’s own output option. sort has -o, which reads all its input before opening the output file:
sort names.txt -o names.txt
It’s the cleanest solution when it exists. uniq doesn’t have it; sort -u -o covers many cases.
2. A temporary file and mv. Works with any command:
sort names.txt > names.sorted && mv names.sorted names.txt
The && means the mv only happens if the command succeeded; if something fails, the original stays as it was. If you use mktemp for the temporary name (a good idea in /tmp or in scripts), be careful: mktemp creates the file with 0600 permissions, and after the mv your file inherits them. In the test, a names.txt with -rw-r--r-- ended up as -rw-------. Fix it with chmod --reference=names.txt "$tmp" before the mv. And remember that mv replaces the file with another one: hard links pointing at the original will keep pointing at the old version.
3. sed -i for text changes.
sed -i.bak 's/alice/alicia/' names.txt
It edits “in place”, though internally it does the same as option 2: it writes a new file and swaps it in for the old one. That’s why it breaks hard links (we checked: the link kept showing the old contents) and, without --follow-symlinks, turns a symbolic link into a regular file. The -i.bak suffix keeps a copy of the original.
4. sponge, from the moreutils package.
sudo apt install moreutils # dnf install moreutils on Fedora
sort names.txt | sponge names.txt
sponge soaks up all its input and only opens the target file once the pipe closes. With sponge -a it appends instead of replacing. Its advantage is that it writes to the same file, so it keeps permissions, owner and hard links. The catch: if the command on the left fails halfway, sponge still writes whatever it received.
An atomic lock in one line
Because noclobber creates files with O_EXCL, it’s useful for something that has nothing to do with mistakes: stopping two copies of a script from running at the same time.
if ( set -C; echo $$ > /tmp/job.lock ) 2>/dev/null; then
trap 'rm -f /tmp/job.lock' EXIT
echo "got the lock"
# ... work ...
else
echo "another copy is already running (PID $(cat /tmp/job.lock))" >&2
exit 1
fi
The parentheses open a subshell so set -C only lasts for that moment. If /tmp/job.lock doesn’t exist, it’s created with the PID inside and the condition is true; if it exists, the redirection fails. To check it really is atomic we launched 50 copies in parallel, all trying to take the same lock: exactly one won.
The trap ... EXIT is essential. Without it, if the script dies on an error, the lock stays put and the next run will think another one is going. Even then not everything is covered: a kill -9 or a power cut leaves the file orphaned, which is why the example stores the PID, so you can check by hand whether that process is still alive.
For production locks, flock (from util-linux, installed on almost every distribution) is the better tool. The kernel releases the lock when the process dies, however it dies:
exec 9>/tmp/job.lock
flock -n 9 || { echo "another copy is already running" >&2; exit 1; }
The noclobber trick is still handy when flock isn’t around or in a minimal POSIX shell.
In zsh, dash and fish
zsh has the same idea under another name. In zsh the option is called CLOBBER and it’s on by default; turning it off is the same as turning noclobber on:
setopt noclobber # or: unsetopt clobber
$ sort names.txt > names.txt
zsh: file exists: names.txt
Both >| and >! force the overwrite. There’s an important difference from bash that we ran into while testing: in zsh, with noclobber, >> fails if the file doesn’t exist:
$ echo c >> new.txt
zsh: no such file or directory: new.txt
Use >>| or >>! for a one-off, or setopt append_create so >> creates files as usual. zsh also has setopt clobber_empty, which allows overwriting files that exist but are empty. The settings go in ~/.zshrc.
dash, the /bin/sh on Debian and Ubuntu, follows POSIX to the letter: set -C and >| work the same. The message is different (cannot create d.txt: File exists) and the exit status is 2, not 1.
fish has no global option, but it does have its own operator: >? only writes if the file doesn’t exist. In fish 4.0.2:
> echo b >? ff.txt
warning: The file 'ff.txt' already exists
There’s no way to make > behave like >? everywhere, so in fish the protection depends on remembering to use it.
Other safety nets
noclobber locks one door. The others need their own locks:
cp -iandmv -iask before overwriting. Many distributions (Fedora, RHEL) already alias them for root. Careful: with an alias like that,cpin a script won’t ask, because scripts don’t load aliases.cp --update=nonesilently skips files that already exist, and--update=none-failalso returns an error. In coreutils 9.7 the help text marks-nas deprecated in favour of these two.rm -Iasks once when you’re about to delete more than three files or recurse. Far less annoying thanrm -i.- Version control. Files you care about belong in git. A
git checkout -- fileundoes an accidental wipe in a second. For/etc,etckeeperdoes the same automatically. - Filesystem snapshots. With Btrfs or ZFS (Snapper, Timeshift, sanoid), recovering a file from an hour ago is just a copy from the snapshot.
- A copy before touching anything delicate:
cp -a file file.$(date +%F)takes a second.
If you’re new to the terminal, our list of commands sysadmins actually use helps put all this in context, and the history of Bash and the Unix shell explains where options like this come from: bash took it from the C shell and the Korn shell.
Cheat sheet
| I want to… | Command |
|---|---|
| Turn the protection on | set -o noclobber or set -C |
| Turn it off | set +o noclobber or set +C |
| Check whether it’s on | set -o | grep noclobber or [[ $- == *C* ]] |
| Overwrite on purpose | command >| file (zsh: also >!) |
| Keep it always on | set -o noclobber in ~/.bashrc (zsh: setopt noclobber in ~/.zshrc) |
| Sort in place | sort file -o file |
| Any command in place | command file | sponge file |
| Quick lock | ( set -C; echo $$ > f.lock ) 2>/dev/null |
| Robust lock | exec 9>f.lock; flock -n 9 |
| Copy without overwriting | cp --update=none-fail source dest |
How we tested this
All output comes from Docker containers using the debian:13 image (Debian 13.7, ARM64): GNU bash 5.2.37, coreutils 9.7, moreutils 0.69, strace 6.13, zsh 5.9, dash 0.5.12 and fish 4.0.2. The openat calls with O_TRUNC and O_EXCL were captured with strace -f -e trace=openat,newfstatat on bash -c and bash -C -c. The lock atomicity test launched 50 background subshells against the same file and counted how many succeeded.
To repeat it:
docker run --rm -it --name lab-noclobber debian:13 bash
apt-get update && apt-get install -y moreutils strace zsh fish
cd /tmp && printf "carol\nalice\nbob\n" > names.txt
sort names.txt > names.txt; wc -c names.txt # 0 bytes
printf "carol\nalice\nbob\n" > names.txt
set -o noclobber
sort names.txt > names.txt # cannot overwrite existing file
Sources: the GNU Bash manual on redirections and the set builtin; the POSIX specification for set and shell redirection; the zsh manual on redirection and options; the fish documentation on redirection; the man pages for open(2), flock(1) and mktemp(1) on man7.org; the GNU coreutils cp manual; and the moreutils page.
