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 fails
1tmpdir=$(mktemp -d) || exit 1
# Always delete it on exit, whatever the reason
2trap 'rm -rf "$tmpdir"' EXIT
# Work file inside the temp directory
3work_file="$tmpdir/data.txt"
# Quoted path stays one word even if it contains spaces
4echo "Processing..." > "$work_file"
# ${INPUT:-} gives "" when unset, so this also works under set -u
5if [[ -z "${INPUT:-}" ]]; then
# Error messages go to stderr
6 echo "INPUT not set" >&2
7 exit 1
8fi
# Allow only letters, digits and _; exit on anything else
9[[ "$INPUT" =~ ^[a-zA-Z0-9_]+$ ]] || exit 1
# Reached only with valid input
10cat "$work_file"

Output

INPUT not set
Practice typing this code

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

More Shell examples at level 5

← Shell typing practice