Shell trust boundaries and argument injection
A trust boundary separates data you control from data supplied by a caller, file or service. Start by defining which commands, options and inputs a script accepts. Quoting a scalar expansion preserves it as one argument; it does not make that argument harmless. A utility may interpret a leading hyphen as an option, a value as a regular expression, or a format string as instructions. Use a fixed format for printf, fixed command names, and the end-of-options marker -- where the utility supports it. For a literal text search, use grep -F -e "$needle" -- "$file"; -e explicitly marks the pattern and -F disables regex interpretation. Validate paths against the intended contract; quoting does not restrict them to an allowed directory. For small unsigned decimal numbers, first check ASCII digits and a length bound under C locale, then use explicit base 10. Reject unexpected values before performing effects. The examples use harmless fixture data, not attacks against real systems. The numeric example accepts exactly one argument of one to three ASCII digits. An empty string, missing argument, extra argument or longer digit sequence is rejected before arithmetic.
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.
Keep literal data literal
Expected stdout:
[100% ready; *]The fixed format and quoting preserve the percent, semicolon and wildcard as data.
Protect utility operands
printf '%s\n' 'a.b' 'axb' '-n' > ./-report || exit 1needle='a.b'grep -F -e "$needle" -- -report || exit 1needle='-n'grep -F -e "$needle" -- -report || exit 1Expected stdout:
a.b-nThe fixed-string pattern and option boundary are separate protections.
Validate before arithmetic
number() { [[ $# == 1 ]] || return 2 local raw=$1 LC_ALL=C [[ $raw =~ ^[0-9]{1,3}$ ]] || return 2 printf '%s\n' "$((10#$raw))"}number 08 || exit 1number abc || printf 'rejected=%s\n' "$?"Expected stdout:
8rejected=2Only bounded digit strings enter arithmetic. The explicit base avoids octal interpretation.
Common mistakes
Quoting is necessary but not sufficient. Never use external text as a printf format or assume every utility supports --.
Practice
In a private directory create a file with a leading hyphen in its name, search for a literal dot, and test numeric inputs 08, 9999 and abc. Explain which layer validates each input.
Next: Avoid unsafe dynamic execution