R308 Build no target path of a destructive command from a part that may be empty
Superseded by R315 Check every part of a destructive shell command's target path before the command.
Never let a command that deletes, overwrites or empties files take a target path built from a variable or a command’s output that may be empty or unset: write the path literally, or have the command first check that each such part of it is set and not empty, and stop when one is not.
Reason
An empty or unset variable, or a command whose output is empty, drops out of a path without an error: <dir>/<name> becomes <dir>/, and <root>/<name> with both empty becomes /, the root of the file system. A recursive delete of that path removes far more than was meant, and cannot be undone. Agents pursue goals only by legitimate means, never by destructive ones (Art. II §6(1)), and a command whose target can widen this way, unseen, is destructive by its shape whatever its author meant.
Verification
A command that deletes, overwrites or empties files is one such as a delete, recursive or not, a move or copy onto an existing path, a write that truncates a file, a sync that deletes what the source lacks, or the cleaning of a directory, whether it runs in a shell, in a script or as a call in a program’s code. The parts of a target path are the variables and the command outputs, such as command substitutions or the results of calls, that it is built from, directly or through another variable: a variable whose value is built from other parts brings them into the path too, so a check of that variable alone does not cover them. A part may be empty or unset unless the same command or script gave it a value that is not empty, written literally, before the path is built; a command’s output, an argument, an environment variable and a value read from a file may all be empty.
Checks that meet this rule include, in a POSIX shell, writing the variable in the path as ${VAR:?}, running [ -n "$VAR" ] || exit 1 before the command, or putting a command substitution into a variable first and checking that, as in n=$(…); [ -n "$n" ] || exit 1, and in any language, checking that the resolved target lies under the root expected for it and is not that root itself. set -u alone does not meet it, since it stops on an unset variable but not on an empty one.
Violated when an agent runs or writes such a command whose target path is built from a part that may be empty or unset and that no check before the command stops on.