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.
xxxxxxxxxx
set -o errexit -o noclobber
working_directory="$(mktemp --directory)"
bin_path="${working_directory}/secret.bin"
hex_path="${working_directory}/secret.hex"
dd bs=32 count=1 if=/dev/urandom of="$bin_path" status=none
# shellcheck disable=SC2094
xxd -cols 32 -plain "$bin_path" > "$bin_path"
logger "New secret available in ${hex_path}."
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.
Get unlimited access to The newline Guide to Bash Scripting, plus 70+ \newline books, guides and courses with the \newline Pro subscription.
