Avoid unsafe dynamic execution
Separate command selection from argument data. eval combines arguments into shell text and evaluates it; quoting its input does not stop that evaluation. bash -c likewise runs a command string, so keep that string fixed and pass values as positional arguments when a child shell is genuinely necessary. For ordinary tasks, use an array with a trusted command and fixed options, then expand it as "${cmd[@]}". Use explicit case dispatch for supported actions; reject unknown actions rather than executing them as command names. A sourced file executes in the current shell: it is code, not a configuration parser. Read simple configuration with a narrow data grammar, validate values and reject unsupported keys. Avoid arbitrary variable names, arithmetic expressions and nameref targets from external input. These patterns reduce interpretation boundaries but do not make an arbitrary executable or its arguments safe. The configuration example accepts exactly one record of known small NUL-free text, with or without a final newline. It rejects additional records. It is not a general binary-safe or resource-bounded configuration parser.
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.
Use command arrays
Expected stdout:
[daily report][*][]Each element becomes an argument without a second shell parse.
Dispatch only supported actions
dispatch() { case ${1-} in show) printf 'show\n' ;; count) printf 'count\n' ;; *) return 2 ;; esac}dispatch show || exit 1dispatch other || printf 'rejected=%s\n' "$?"Expected stdout:
showrejected=2The caller chooses from an explicit allowlist, not arbitrary executables.
Parse configuration as data
printf 'mode=test\n' > app.conf || exit 1mapfile -t lines < app.conf || exit 1(( ${#lines[@]} == 1 )) || exit 2line=${lines[0]}case $line in mode=dev|mode=test) mode=${line#mode=} ;; *) exit 2 ;;esacprintf 'mode=%s\n' "$mode"Expected stdout:
mode=testThis demonstration validates exactly one record of a small NUL-free text fixture without executing it. A production parser must enforce size and encoding limits independently.
Common mistakes
Do not build executable shell strings from user data or source downloaded configuration. Arrays are argument containers, not a sandbox.
Practice
Write a dispatcher supporting show and count only. Test an empty action and an unknown action; neither should run a command. Add a literal value with spaces.
Next: PATH, startup and environment safety