Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps