How to Prevent a Bash Script From Overwriting Files With noclobber

“Clobbering” a file has a very specific meaning in Bash — it’s when you use the > redirect operator to overwrite an existing regular file. Setting noclobber results in a non–zero exit code when a script tries to clobber a file, leaving the file untouched. See for example this script, intended to get 32 bytes of random binary data and convert it to hexadecimal so that it can be stored in a configuration file:

noclobber also applies to symbolic links to regular files. Some special files like /dev/null are not actually changed when you attempt to clobber them. noclobber is smart enough to allow such redirects.

There’s a simple typo: the xxd output should be redirected to $hex_path, but instead it’s redirected back to the already existing file.

This lesson preview is part of the The newline Guide to Bash Scripting course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to The newline Guide to Bash Scripting, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course The newline Guide to Bash Scripting