Bash Script Security Fundamentals
A Bash script is a program, and like any program it can be tricked into doing something its author never intended. Shell scripts are especially exposed for three reasons. First, the shell re-interprets text: a value that contains spaces, *, - or $( ) can change the meaning of a command if it is not handled carefully. Second, scripts usually run with real power: they delete files, restart services, copy backups and often run as root or from cron. Third, scripts depend on their environment: the PATH, the current folder, the umask and many variables that the caller controls.
Script security is therefore about one idea: the script must behave the same way no matter what data and environment it receives. This lesson explains where attacks and accidents come from and introduces the basic defences. The following lessons go deeper into individual topics: command injection (155), quoting user input (156), eval (157), secrets (158), least privilege (159), destructive commands (160), path validation (161) and ShellCheck (162).
Understanding the Threat Model
A threat model is a list of the things that could go wrong and who could cause them. For a shell script, the questions are: what data does the script trust, and who controls it?
| Source of data | Example | Who may control it |
|---|---|---|
| Command-line arguments | ./deploy.sh "$branch" | the caller, a web form, a CI job |
| Environment variables | PATH, HOME, BASH_ENV, IFS | the caller, a parent process |
| File names | the result of * or find | anyone who can create files in the folder |
| File contents | a configuration file, a CSV upload | whoever can write the file |
| Command output | curl, git log, ls | remote servers, repository authors |
| Shared locations | /tmp, shared folders | every user on the machine |
Data from any of these sources is untrusted unless you know exactly who wrote it. Most real problems are not deliberate attacks but accidents caused by unexpected data: a file name with a space, a variable that turned out empty, a folder with a name beginning with -. The same defences protect against both.
Principle 1: Quote Every Expansion
An unquoted variable undergoes word splitting and filename expansion (lessons 53 and 55). The value is cut into words at spaces, and each word that looks like a pattern is replaced by matching file names.
The following examples run in a folder that contains report.txt, notes.txt, my file.txt and a file named -l:
f='my file.txt'
cat $f
cat "$f" && echo "quoted ok"
cat: my: No such file or directory
cat: file.txt: No such file or directory
quoted ok
Unquoted, one file name became two arguments. With rm instead of cat, the wrong files could be deleted. A value that contains a wildcard is even more surprising:
pat='*'
echo $pat
echo "$pat"
-l my file.txt notes.txt report.txt
*
The unquoted $pat turned into the list of every file in the folder. The rule is simple: write "$var", "$(command)" and "${array[@]}" in double quotes, unless you can explain why splitting is wanted in that exact place.
Principle 2: Separate Options from File Names
Most commands treat an argument that starts with - as an option. A file name that starts with - can therefore change what a command does. In the same folder:
ls *
-rw-r--r-- 1 ana ana 0 Nov 24 06:59 my file.txt
-rw-r--r-- 1 ana ana 0 Nov 24 06:59 notes.txt
-rw-r--r-- 1 ana ana 0 Nov 24 06:59 report.txt
The glob expanded to -l my file.txt notes.txt report.txt, and ls read the file -l as the "long listing" option. With a more dangerous command and a file named -rf or --delete, the effect could be serious. There are two standard defences:
ls -- * # "--" means: no more options after this point
ls ./* # every name now starts with "./", never with "-"
-l
my file.txt
notes.txt
report.txt
./-l
./my file.txt
./notes.txt
./report.txt
Put -- before file arguments in scripts (rm -- "$file", mv -- "$a" "$b"), and prefer ./* to * when you expand file names in the current folder.
Principle 3: Validate Input with an Allowlist
Quoting stops the shell from misreading data, but it does not stop the data itself from being harmful. A quoted value of ../../etc is still a path that leaves the intended folder. Every input should therefore be validated before it is used.
There are two ways to validate. A denylist rejects known bad values ("no ;, no $, no .."). An allowlist accepts only known good values ("letters, digits, dash and underscore, at most 64 characters"). Allowlists are much safer, because an attacker only needs to find one character you forgot to deny, while an allowlist rejects everything you did not explicitly permit.
for n in 5 -1 abc '1;id' '$(id)' 08; do
if [[ $n =~ ^[0-9]+$ ]]; then
echo "$n ok $((10#$n))"
else
echo "$n rejected"
fi
done
5 ok 5
-1 rejected
abc rejected
1;id rejected
$(id) rejected
08 ok 8
The regular expression ^[0-9]+$ accepts only digits from start to end. 10#$n forces base 10, so 08 is not read as an invalid octal number (lesson 49).
Why Validating Numbers Matters: Arithmetic Evaluation
Numeric validation is not just about clean error messages. Inside (( )), $(( )), let and array indexes, Bash evaluates a variable's value as an arithmetic expression, and that evaluation can run commands hidden in array subscripts:
x='a[$(echo INJECTED >&2)]'
(( y = x + 1 ))
echo "y=$y"
INJECTED
y=1
The value of x was never meant to be code, yet the command inside it ran. If x had come from user input, an attacker could run any command. The defence is to check that a value contains only digits (with an allowlist like the one above) before it reaches arithmetic. Lesson 155 covers this and other injection paths in detail.
Principle 4: Control the Environment
A script inherits its environment from whoever starts it. Several variables change how Bash and other programs behave.
PATH
When a script runs ls, Bash searches the folders in PATH from left to right and runs the first ls it finds. If an attacker can put a folder they control in front of the system folders, they can replace any command. This example creates a fake ls in a folder named evil:
mkdir -p evil
printf '#!/bin/sh\necho "fake ls ran as $(id -un)"\n' > evil/ls
chmod +x evil/ls
PATH="$PWD/evil:$PATH" bash -c 'ls report.txt'
PATH="$PWD/evil:$PATH" bash -c 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin; ls report.txt'
fake ls ran as ana
report.txt
In the first command, the fake program ran instead of the real ls. In the second, the script set its own PATH to trusted system folders first, and the real ls ran. Scripts that run with elevated rights, or from shared environments, should set PATH explicitly at the top. Never include . (the current folder) or a world-writable folder in PATH.
IFS, CDPATH and BASH_ENV
| Variable | Effect if the caller changes it | Defence |
|---|---|---|
IFS | changes how unquoted values and read split words | set IFS=$' \t\n' at the top |
CDPATH | makes cd name go to a different folder | unset -v CDPATH, or use cd -- ./name |
BASH_ENV | names a file that non-interactive Bash runs before the script | start the script with a clean environment |
BASH_ENV is special because it acts before the first line of the script runs:
printf 'echo "BASH_ENV code ran"\n' > env.sh
BASH_ENV=./env.sh bash -c 'echo script body'
env -i PATH=/usr/bin:/bin bash -c 'echo clean env: ${BASH_ENV:-unset}'
BASH_ENV code ran
script body
clean env: unset
A script cannot protect itself from BASH_ENV by unsetting it, because it is too late by then. For automated jobs (cron, systemd, sudo), the caller should start the script with a minimal environment. sudo and systemd already do this by default, and env -i does it by hand.
umask and File Permissions
The umask decides the permissions of new files (lesson 72). The common default 022 makes new files readable by everyone on the machine. A script that writes backups, logs with personal data or anything containing secrets should set a stricter mask first:
(umask 022; touch pub.txt)
(umask 077; touch priv.txt)
stat -c '%A %n' pub.txt priv.txt
-rw-r--r-- pub.txt
-rw------- priv.txt
With umask 077, only the owner can read or write the files the script creates.
Principle 5: Use Safe Temporary Files
A script that writes to a fixed name such as /tmp/backup.tmp is vulnerable. /tmp is shared by all users, so another user can create that name first, for example as a symbolic link pointing to an important file, and the script will then overwrite the target. This kind of bug is called a race condition: the outcome depends on who acts first.
mktemp (lesson 113) avoids the problem. It creates a new file with an unpredictable name and owner-only permissions, and it fails rather than reuse an existing name:
t=$(mktemp)
stat -c '%A' "$t"
echo "$t"
-rw-------
/tmp/tmp.k3Vq9ZbX2c
Combine mktemp with a trap on EXIT (lesson 124) so the file is removed even when the script fails.
Principle 6: Fail Safely
A script that keeps running after an error can do damage with half-finished data, for example deleting the old backup after the new one failed. The strict-mode options (lessons 119 to 121) make failures visible:
set -estops the script when a command fails (with the caveats explained in lesson 119);set -utreats an unset variable as an error, so a typo such asrm -rf "$BUILDDIR/"with an unset variable does not becomerm -rf "/";set -o pipefailreports a failure anywhere in a pipeline.
Failing safely also means writing results atomically: build the result in a temporary file and move it into place with mv only when it is complete. mv within one file system replaces the name in a single step, so other programs never see a half-written file.
Principle 7: Read Data, Do Not Execute It
Data should never become code. The main ways this happens are:
eval "$string", which runs any text as a command (lesson 157);source "$file"on a file that someone else can write;bash -c "$string"orssh host "$string"with user data pasted into the string (lesson 155);- arithmetic on unvalidated values, as shown above.
Reading input safely also includes small details. read without -r treats backslashes as escape characters, which silently changes the data:
printf 'a\\tb\n' | { read line; echo "[$line]"; }
printf 'a\\tb\n' | { read -r line; echo "[$line]"; }
[atb]
[a\tb]
Always use read -r unless you specifically want backslash processing.
Setuid and sudo
On Linux, the setuid permission bit, which makes a program run with its owner's rights, is ignored for scripts, because scripts proved impossible to make safe that way. To give a script elevated rights, use sudo with a rule that allows exactly that script, owned by root and not writable by anyone else. Lesson 159 covers this in detail.
A Complete Example: A Hardened Backup Script
archive-project.sh archives one project folder from ~/projects into ~/backups and deletes that project's old archives. The task is ordinary, but the script applies every principle from this lesson, so it is safe to call from a web hook, a chat bot or a sudo rule where the project name comes from someone else.
#!/usr/bin/env bash
# archive-project.sh: archive one project folder into a private backup file
# usage: archive-project.sh PROJECT_NAME [KEEP_DAYS]
# PROJECT_NAME folder name under $PROJECTS_DIR (letters, digits, _ . -)
# KEEP_DAYS delete this project's archives older than N days (default 30)
# 1. Predictable environment ------------------------------------------------
set -euo pipefail
PATH=/usr/local/bin:/usr/bin:/bin # only trusted system folders
export PATH
IFS=$' \t\n' # the default word separators
umask 077 # new files: owner only
unset -v CDPATH # would change where "cd" goes
readonly PROJECTS_DIR=${PROJECTS_DIR:-$HOME/projects}
readonly BACKUP_DIR=${BACKUP_DIR:-$HOME/backups}
readonly PROG=${0##*/}
die() { printf '%s: error: %s\n' "$PROG" "$*" >&2; exit 1; }
# 2. Validate every input against an allowlist --------------------------------
(( $# >= 1 && $# <= 2 )) || { echo "usage: $PROG PROJECT_NAME [KEEP_DAYS]" >&2; exit 2; }
name=$1
keep_days=${2:-30}
[[ $name =~ ^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$ ]] ||
die "invalid project name: ${name@Q}"
[[ $name != *..* ]] || die "invalid project name: ${name@Q}"
[[ $keep_days =~ ^[0-9]{1,4}$ ]] || die "KEEP_DAYS must be a whole number: ${keep_days@Q}"
keep_days=$((10#$keep_days)) # "08" -> 8, never treated as octal
src=$PROJECTS_DIR/$name
[[ -d $src && ! -L $src ]] || die "not a project folder: ${src@Q}"
# 3. Private temporary file, always cleaned up --------------------------------
mkdir -p -- "$BACKUP_DIR"
tmp=$(mktemp "$BACKUP_DIR/.partial.XXXXXXXXXX")
trap 'rm -f -- "$tmp"' EXIT
# 4. Do the work with quoted variables and "--" before file arguments ---------
stamp=$(date +%Y%m%d-%H%M%S)
dest=$BACKUP_DIR/$name-$stamp.tar.gz
[[ ! -e $dest ]] || die "archive already exists: ${dest@Q}"
tar -czf "$tmp" -C "$PROJECTS_DIR" -- "$name"
mv -- "$tmp" "$dest" # appears only when complete
# 5. Delete old archives of this project only ---------------------------------
ts='[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]'
find "$BACKUP_DIR" -maxdepth 1 -type f -name "$name-$ts.tar.gz" \
-mtime +"$keep_days" -print -delete | sed 's/^/removed old archive: /'
printf 'created %s (%s)\n' "$dest" "$(stat -c '%A %s bytes' -- "$dest")"
How It Works
- Section 1 makes the environment predictable. Strict mode stops on errors and unset variables;
PATHcontains only system folders, so a plantedtarorfindcannot run;IFSis reset;umask 077makes the archive private;CDPATHis removed. The folder settings can be changed throughPROJECTS_DIRandBACKUP_DIR, but they are fixed withreadonlyafterwards. - Section 2 validates both inputs with allowlists. The project name must start with a letter or digit, so it can never begin with
-or., and may contain only letters, digits,_,.and-, up to 64 characters. A slash is impossible, and the extra..check blocks names likea..bthat are confusing even though they cannot leave the folder.KEEP_DAYSmust be 1 to 4 digits, which keeps it away from arithmetic injection, and10#prevents octal surprises. Error messages show the rejected value with${name@Q}(lesson 152), so hidden characters are visible. - The folder check requires a real folder (
-d) that is not a symbolic link (! -L), so a link inside~/projectscannot make the script archive/etcor another user's files. - Section 3 creates the temporary file with
mktempinside the backup folder, so the finalmvstays on one file system and is atomic. Thetrapremoves the partial file however the script ends. - Section 4 quotes every variable and puts
--before file arguments. The script refuses to overwrite an existing archive. - Section 5 deletes old archives with a precise pattern: the project name, a dash and a timestamp of exactly 8 and 6 digits. A shorter pattern such as
"$name-*"would make the projectsitedelete the archives ofsite-2. The pattern contains no characters from user input except the validated name. - The last line prints the result with the permissions, which confirms that the archive is private.
Running the Complete Example
The projects folder contains site, site-2 and a symbolic link etc-link pointing to /etc. Each project has an archive that is 45 days old.
./archive-project.sh site; echo "status $?"
./archive-project.sh site-2 7; echo "status $?"
removed old archive: /home/ana/backups/site-20261010-090000.tar.gz
created /home/ana/backups/site-20261124-070006.tar.gz (-rw------- 172 bytes)
status 0
removed old archive: /home/ana/backups/site-2-20261010-090000.tar.gz
created /home/ana/backups/site-2-20261124-070007.tar.gz (-rw------- 153 bytes)
status 0
The run for site removed only the old site archive and left the one for site-2 alone; the second run removed that one. Both new archives are readable only by their owner.
Hostile and mistaken input is rejected before anything is touched:
for arg in '../../etc' 'site;id' '$(id)'; do ./archive-project.sh "$arg"; echo "status $?"; done
./archive-project.sh site 1e3; echo "status $?"
./archive-project.sh missing; echo "status $?"
./archive-project.sh etc-link; echo "status $?"
./archive-project.sh; echo "status $?"
archive-project.sh: error: invalid project name: '../../etc'
status 1
archive-project.sh: error: invalid project name: 'site;id'
status 1
archive-project.sh: error: invalid project name: '$(id)'
status 1
archive-project.sh: error: KEEP_DAYS must be a whole number: '1e3'
status 1
archive-project.sh: error: not a project folder: '/home/ana/projects/missing'
status 1
archive-project.sh: error: not a project folder: '/home/ana/projects/etc-link'
status 1
usage: archive-project.sh PROJECT_NAME [KEEP_DAYS]
status 2
A path that tries to leave the folder, a name with a command separator, a command substitution, a number in scientific notation, a missing folder and a symbolic link to a system folder were all refused with a clear message and a non-zero status.