The `noclobber` Shield: Preventing Accidental Overwrites

Quick Tip

The `noclobber` Shield: Preventing Accidental Overwrites

Challenge: You’re working in the terminal, maybe scripting or redirecting output, and you accidentally overwrite an important file with an empty or incorrect one. This is a common and frustrating mistake.

The Solution: Use the `set -o noclobber` shell option to prevent accidental overwrites when redirecting output.

set -o noclobber echo "This will not overwrite existing_file.txt" > existing_file.txt # If existing_file.txt already exists, this command will fail with an error. # To overwrite, you would need to explicitly unset noclobber or use ! # echo "This will overwrite existing_file.txt" >! existing_file.txt set +o noclobber # To disable noclobber

Why it works: When `noclobber` is enabled, the shell will prevent the `>` (output redirection) operator from overwriting an existing file. This acts as a safety net against accidental data loss. To override this protection, you can use `>!` or temporarily unset `noclobber` with `set +o noclobber`.

Pro-Tip: You can add `set -o noclobber` to your `~/.bashrc` file to have this protection enabled by default for all your interactive shell sessions.

Linux Tips & Tricks | © ngelinux.com | 6/1/2026

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments