Safe temporary files and filesystem races
Use a private, trusted workspace for files. umask 077 removes group and other permissions from newly created objects, subject to requested modes and filesystem ACL behavior; it does not change existing files. mktemp -d creates a unique directory rather than merely suggesting a name. Check creation before use, keep its path quoted, and clean up only resources owned by the script. Prefer narrow cleanup such as removing the known file then rmdir, rather than recursive deletion of an unchecked variable. An existing symbolic link may point elsewhere; [[ -L path ]] can identify a link at the moment of inspection, but a separate check followed by open is not atomic. In an attacker-writable directory, paths can change between operations. Even canonicalization with realpath cannot make later opens race-free. Security-critical operations may require a reviewed helper using descriptor-relative APIs and appropriate no-follow/exclusive-open flags; shell prechecks are not a substitute. The examples operate only in private fixture directories with no concurrent adversary. The cleanup check verifies both absence of the directory and absence of a dangling symbolic link at that name. These checks are observations in a private directory, not atomic guarantees in a shared directory.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Observe file creation permissions
umask 077printf 'fixture\n' > private.txt || exit 1mkdir private-dir || exit 1stat -c '%a' private.txt private-dirExpected stdout:
600700Observed GNU/Linux modes for fresh objects without a default ACL.
Create and clean an owned temporary directory
umask 077tmp=$(mktemp -d ./work.XXXXXXXX) || exit 1printf 'ready\n' > "$tmp/report" || exit 1cat "$tmp/report" || exit 1rm -- "$tmp/report" && rmdir -- "$tmp" || exit 1[[ ! -e $tmp && ! -L $tmp ]] && printf 'cleaned\n' Expected stdout:
readycleanedThe path is created by mktemp and cleanup names only the owned objects.
Detect a fixture symlink
printf 'original\n' > target || exit 1ln -s target link || exit 1if [[ -L link ]]; then printf 'link rejected\n'else printf 'regular candidate\n'ficat targetExpected stdout:
link rejectedoriginalThis demonstrates a link check, not a safe check-then-open algorithm in a shared directory.
Common mistakes
Do not use predictable names in shared writable directories or assume test -L followed by open is race-free.
Practice
In a fresh directory create a private temporary directory, write one known file, verify its mode with GNU stat, and remove only that file and directory. Explain why a link precheck is insufficient in a shared directory.
Next: Secrets and diagnostic logging