Secure Script Practices in Shell
Level 5250 keystrokes
A defensive script: it creates a private temp directory with mktemp -d, removes it on exit with a trap, checks that INPUT is set and that it contains only safe characters, and quotes every variable. With INPUT unset it prints "INPUT not set" (to stderr) and exits.
Shell code
# Create a private temp directory; stop if mktemp fails1tmpdir=$(mktemp -d) || exit 1# Always delete it on exit, whatever the reason2trap 'rm -rf "$tmpdir"' EXIT# Work file inside the temp directory3work_file="$tmpdir/data.txt"# Quoted path stays one word even if it contains spaces4echo "Processing..." > "$work_file"# ${INPUT:-} gives "" when unset, so this also works under set -u5if [[ -z "${INPUT:-}" ]]; then # Error messages go to stderr6 echo "INPUT not set" >&27 exit 18fi# Allow only letters, digits and _; exit on anything else9[[ "$INPUT" =~ ^[a-zA-Z0-9_]+$ ]] || exit 1# Reached only with valid input10cat "$work_file"Output
INPUT not set
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Shell code and how often they appear.
"× 16$× 8-× 7[× 5]× 5_× 4.× 4|× 4=× 3'× 2