What does `set -o noclobber` do and when is it useful?
AdvancedConceptFunctions, exit codes, strict mode and traps
Answer
With set -C (noclobber), > refuses to overwrite an existing file (cannot overwrite existing file); >| forces it. It is useful as an atomic "create if not exists" lock in POSIX sh:
if ( set -C; echo "$$" > /var/run/myjob.lock ) 2>/dev/null; then
trap 'rm -f /var/run/myjob.lock' EXIT
else
echo "already running (pid $(cat /var/run/myjob.lock))" >&2; exit 0
fi
On Linux, flock is more robust because the lock disappears automatically if the process is killed.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerWhat does `set -e` do, and where does it NOT cause an exit?AdvancedExplain `set -euo pipefail` line by line, and add the `-E` flag.Beginner