Noclobber and redirection failures
set -o noclobber (or set -C) prevents ordinary > redirection from truncating existing regular files. set +C disables it; >| requests an explicit override. Append is still possible with >>; noclobber is not a general filesystem security policy or a backup. A redirection can fail because a path does not exist for input, a parent directory is absent, a descriptor is closed, or an expanded filename is ambiguous. If Bash cannot establish a redirection, the affected command does not execute normally and reports a nonzero status. Earlier redirections may already have changed files, so do not treat a failed command as transactional. Handle expected failure with if command ...; then ...; else ...; fi and preserve status immediately if needed. Shell-generated diagnostics appear on whichever stderr destination applies when failure occurs. Avoid using test -e as a guarantee against concurrent changes. These examples demonstrate ordinary Bash 5.2 behavior in fresh noninteractive shells, not all POSIX special-builtin failure cases. A successful else branch may make the complete if command return zero even when its condition failed. Save or propagate the original status if the surrounding application needs to report failure. The first two fixtures check their initial writes before demonstrating noclobber.
Practical examples
Run each example separately in a fresh Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Protect a fixture and append
printf 'original\n' > log.txt || exit 1set -Cif { printf 'replace\n' > log.txt; } 2> error.txt; then printf 'unexpected\n'else printf 'blocked=%s\n' "$?"fiprintf 'extra\n' >> log.txt || exit 1cat log.txtExpected stdout:
blocked=1originalextraThe group sends the expected shell diagnostic to error.txt; append remains allowed.
Explicit override on disposable data
printf 'old\n' > fixture.txt || exit 1set -o noclobberprintf 'new\n' >| fixture.txt || exit 1cat fixture.txtExpected stdout:
newThe override intentionally truncates only the fixture created here.
A failed input prevents the body
work() { printf 'body ran\n'; }if { work < missing.txt; } 2> error.txt; then printf 'unexpected\n'else printf 'not run; status=%s\n' "$?"fiExpected stdout:
not run; status=1The group captures the diagnostic; the function body never prints.
Common mistakes
Do not use >| as a routine fix. Check why redirection failed and choose whether to append, pick a fresh path, or explicitly replace only a disposable file. A successful syntax check does not prove a file can be opened.
Practice
Create a disposable log, enable noclobber, and attempt a second > inside an if. Confirm the original remains, then append a line. Test a missing input path and explain how you know the command body did not run.
Next: Commands, execution and shell state