Bash Script Security Fundamentals

Su Suriya Ravichandran Updated 06 Dec 2026
14 min read ·Lesson 154 of 205

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 dataExampleWho may control it
Command-line arguments./deploy.sh "$branch"the caller, a web form, a CI job
Environment variablesPATH, HOME, BASH_ENV, IFSthe caller, a parent process
File namesthe result of * or findanyone who can create files in the folder
File contentsa configuration file, a CSV uploadwhoever can write the file
Command outputcurl, git log, lsremote servers, repository authors
Shared locations/tmp, shared foldersevery 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

VariableEffect if the caller changes itDefence
IFSchanges how unquoted values and read split wordsset IFS=$' \t\n' at the top
CDPATHmakes cd name go to a different folderunset -v CDPATH, or use cd -- ./name
BASH_ENVnames a file that non-interactive Bash runs before the scriptstart 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 -e stops the script when a command fails (with the caveats explained in lesson 119);
  • set -u treats an unset variable as an error, so a typo such as rm -rf "$BUILDDIR/" with an unset variable does not become rm -rf "/";
  • set -o pipefail reports 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" or ssh 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; PATH contains only system folders, so a planted tar or find cannot run; IFS is reset; umask 077 makes the archive private; CDPATH is removed. The folder settings can be changed through PROJECTS_DIR and BACKUP_DIR, but they are fixed with readonly afterwards.
  • 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 like a..b that are confusing even though they cannot leave the folder. KEEP_DAYS must be 1 to 4 digits, which keeps it away from arithmetic injection, and 10# 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 ~/projects cannot make the script archive /etc or another user's files.
  • Section 3 creates the temporary file with mktemp inside the backup folder, so the final mv stays on one file system and is atomic. The trap removes 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 project site delete the archives of site-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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Bash Script Security Fundamentals and get answers drawn from it.

Signed-in readers only.