Bash’s `noclobber`: The Accidental Overwrite Protector

Quick Tip

Bash’s `noclobber`: The Accidental Overwrite Protector

Challenge: You’re scripting and want to redirect output to a file, but you want to ensure you don’t accidentally overwrite an existing file with crucial data.

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

set -o noclobber echo "This will fail if output.log exists" > output.log # To allow overwriting, you can temporarily unset it: # set +o noclobber # echo "This will overwrite output.log" > output.log # Or, if you really want to overwrite *this time*: # echo "This will overwrite output.log" >| output.log 

Why it works: When `noclobber` is enabled, any attempt to redirect output (`>`) to a file that already exists will result in an error, safeguarding your data. The `>|` operator can be used to explicitly override this protection when needed.

Pro-Tip: Add `set -o noclobber` to your shell’s startup file (e.g., ~/.bashrc) to have this protection enabled by default for all your interactive shell sessions.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Newest
Oldest Most Voted