Linux Command Reference ยท Concepts
Safe shell scripting
How to write safer shell scripts: quote every expansion, avoid injection with eval and unchecked input, create temp files securely and keep secrets out of arguments.
A shell script is a program that glues other programs together, and that is exactly what makes it risky. Data that reaches a command line can turn into options, extra commands or file names that were never intended. Most shell security bugs come from a handful of mistakes: unquoted variables, eval on untrusted text, predictable temp files, and secrets in places other users can see.
This page lists those mistakes and the habit that prevents each one. The goal is not paranoia but a short checklist you apply every time a script touches input you did not write yourself: arguments, file names, environment variables, network data or the contents of a file.
#!/usr/bin/env bash set -euo pipefail tmp=$(mktemp -d) # private, unpredictable trap 'rm -rf -- "$tmp"' EXIT # always cleaned up printf '%s\n' "$1" > "$tmp/in" # quoted, no word splitting
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
The main risks
Unquoted expansions
$var, $(cmd) and $@ without double quotes are split on whitespace and then expanded as globs. A file called a b becomes two arguments; a file called * expands to every name in the directory. Write "$var", "$(cmd)" and "$@" unless you deliberately want splitting. See Quoting pitfalls.
Values that look like options
A user-supplied value such as -rf is taken as an option, not a name. Put -- before file operands (rm -- "$f", grep -e "$pat" -- "$file"), or prefix relative paths with ./. Tools differ in how they handle --, but nearly all of the standard ones support it.
eval and command construction
eval runs a string as code, so anything an attacker controls inside that string is code too. The same is true of bash -c "$input", sh -c, source "$file" with untrusted files, and building a command in a variable then running it. Prefer arrays (cmd=(grep -e "$pat"); "${cmd[@]}"), printf %q for escaping, or avoid dynamic code entirely. See eval.
Temporary files
Names such as /tmp/myscript.$$ are predictable, so another user can create a symlink at that path first and trick your script into overwriting a different file. Use mktemp, which picks an unused name and creates the file or directory with mode 600 or 700, and remove it with a trap ... EXIT.
Secrets
Command-line arguments are visible to every user through ps and /proc/PID/cmdline. Pass passwords through a file descriptor, a file with strict permissions or an environment variable of the single child process, and never log them. Turn off set -x tracing around sensitive lines because it prints expanded values.
PATH and the environment
If PATH contains . or a writable directory, a planted program can shadow ls. Scripts run with elevated rights should set PATH explicitly and call tools by trusted names. Do not trust inherited variables such as IFS, LD_PRELOAD or BASH_ENV in privileged contexts; sudo resets most of them for this reason.
Usage notes
- Fail early.
set -euo pipefailstops on errors, unset variables and failed pipeline stages. It is a safety net, not a substitute for checking inputs. See Bash strict mode. - Validate, do not sanitize. Check that input matches what you expect (
[[ $id =~ ^[0-9]+$ ]]) and reject the rest. Trying to strip bad characters usually misses one. - Use
read -r. Without-r, backslashes in input are interpreted. UseIFS= read -r lineto keep leading spaces too. - Handle odd file names. Names can contain spaces, newlines and leading dashes. Use
find ... -print0 | xargs -0orfind -execrather than parsingls. - Avoid races. Testing a file and then using it (
[ -f x ] && cat x) leaves a gap an attacker can use. Open once and handle the error instead. - Set a safe
umask.umask 077at the top makes new files private by default. Seeumask. - Do not run scripts as root without need. A setuid shell script is unsafe on Linux (the kernel ignores the bit on scripts); use
sudowith a narrow rule. - Lint your scripts. ShellCheck catches most quoting mistakes automatically. It is not installed on our runner, so run it locally.