Validating Paths and User-Supplied Filenames

Su Suriya Ravichandran Updated 06 Dec 2026
18 min read ·Lesson 161 of 205

A script that accepts a file name or a path from someone else, as a command-line argument, a form field passed in by a web handler, a line in a configuration file or the name of an uploaded file, is letting that person choose which file the script opens, creates or deletes. Path validation is the step that decides, before any file is touched, whether the supplied value names a file the script is actually allowed to use.

Without validation, a script that means to read "a document from the docs folder" will happily read ../../etc/shadow, follow a symbolic link to another user's files, or write over .bashrc. This class of bug is called path traversal (or directory traversal), and it is one of the most common security problems in any program that handles file names, shell scripts included. Lesson 160 showed a first version of the containment check; this lesson explains each part of path validation in detail and builds a complete tool around it.

Understanding the Concept

A file name supplied by a user can go wrong in two separate ways.

  1. The text itself is unsafe. It may contain / or .. that climb out of the intended folder, start with - and be read as an option, start with . and reach hidden files such as .env or .git/config, contain newlines or other control characters that break logs and later processing, be empty, or be far too long.
  2. The text looks fine, but the location it reaches is wrong. A harmless-looking name such as guides/escape.txt can be a symbolic link that points somewhere else entirely. Only the file system knows where a path really leads, so the text alone can never prove that a path is safe.

Good validation therefore has two layers:

  • Text rules (an allowlist of characters and shapes) reject obviously unsafe input early and give clear error messages.
  • Resolution and containment turn the path into its real, absolute location with realpath and confirm that this location lies inside an allowed base folder.

Each layer catches problems the other misses, so careful scripts use both.

Why Simple Joining Is Dangerous

The most natural way to use a supplied name is to append it to a base folder:

BASE=/srv/t161/docs
cat -- "$BASE/$1"

The base folder in this lesson's examples is /srv/t161/docs. It holds readme.txt and guides/install.txt, and also a symbolic link guides/escape.txt that points to /srv/t161/other/secret.txt, a file outside the base folder:

bash naive.sh readme.txt
bash naive.sh ../other/secret.txt
bash naive.sh guides/escape.txt
hello
top secret
top secret

The first call does what was intended. The second climbs out of the base folder with ... The third never mentions .. at all; it just names a symbolic link inside the folder, and the kernel follows it. Quoting the variable and using -- (lesson 155) protect against word splitting and option injection, but they do nothing about where the path leads.

Why removing "../" does not work

A common first attempt is to delete every ../ from the input:

p='....//....//other/secret.txt'
echo "${p//..\//}"
../../other/secret.txt

Removing ../ from ....// leaves ../ behind, so the cleaned value is more dangerous than before. Rewriting input until it "looks safe" is fragile. Instead, reject input that does not match the allowed shape, and check where accepted input really leads.

Validating a Single File Name

When the script needs only a file name, with no folders (for example, the name under which to store an upload), the safest approach is a short allowlist: say exactly what a valid name looks like and reject everything else.

export LC_ALL=C

valid_name() {
  local n=$1
  [[ -n $n ]]                    || { echo "empty name"; return 1; }
  [[ $n != .* ]]                 || { echo "starts with a dot"; return 1; }
  [[ $n != -* ]]                 || { echo "starts with a hyphen"; return 1; }
  [[ $n =~ ^[A-Za-z0-9._-]+$ ]]  || { echo "invalid characters"; return 1; }
  (( ${#n} <= 100 ))             || { echo "longer than 100 characters"; return 1; }
}

Each rule has a clear purpose:

RuleWhat it blocks
-n $nan empty value, which would turn $BASE/$n into the folder itself
no leading .., .., and hidden files such as .bashrc and .env
no leading -names that commands would read as options, such as -rf
^[A-Za-z0-9._-]+$/, spaces, quotes, *, $, newlines and every other character not listed
length limitnames longer than the file system allows (usually 255 bytes) or than you want to store

Testing the function against a list of names:

long=$(printf 'a%.0s' {1..120})
for n in report.txt ../etc/passwd a/b '' .. .hidden -rf 'my file.txt' $'bad\nname' café.txt 'x.txt ' "$long"; do
  shown=$(printf '%q' "$n"); (( ${#shown} > 20 )) && shown="${shown:0:12}...(${#n})"
  if msg=$(valid_name "$n"); then printf 'OK      %s\n' "$shown"; else printf 'REJECT  %-20s %s\n' "$shown" "$msg"; fi
done
OK      report.txt
REJECT  ../etc/passwd        starts with a dot
REJECT  a/b                  invalid characters
REJECT  ''                   empty name
REJECT  ..                   starts with a dot
REJECT  .hidden              starts with a dot
REJECT  -rf                  starts with a hyphen
REJECT  my\ file.txt         invalid characters
REJECT  $'bad\nname'         invalid characters
REJECT  $'caf\303\251.txt'   invalid characters
REJECT  x.txt\               invalid characters
REJECT  aaaaaaaaaaaa...(120) longer than 100 characters

printf %q shows every rejected value unambiguously: the trailing space in x.txt appears as x.txt\ , and the newline as $'bad\nname'.

Why LC_ALL=C matters

Bracket ranges such as [A-Za-z] and the length ${#n} depend on the locale. In a UTF-8 locale, Bash counts characters, so café has length 4; in the C locale it counts bytes and the same word has length 5, because é takes two bytes. With some locales and C library versions, ranges like [a-z] also match accented letters, and [[:alpha:]] matches é in C.UTF-8. Setting LC_ALL=C makes the rules work on plain bytes, so the allowlist means exactly what it says on every system, and the length limit counts bytes, which is what the file system's 255-byte name limit (getconf NAME_MAX prints 255 on common Linux file systems) is measured in.

If your users need names with non-ASCII letters, allow them deliberately and test the result in the locale your script runs in. A restrictive allowlist with a clear error message is usually the better choice for names that a script generates or stores.

Validating a Relative Path

When users may name files in subfolders, such as guides/install.txt, apply the text rules to each component of the path. Splitting on / with read -a gives an array of components without any globbing:

check_rel() {
  local p=$1 part
  local -a parts
  [[ $p != /* ]] || { echo "absolute path"; return 1; }
  IFS=/ read -r -a parts <<< "$p"
  for part in "${parts[@]}"; do
    [[ -n $part ]]    || { echo "empty component"; return 1; }
    [[ $part != .* ]] || { echo "component starts with a dot"; return 1; }
    [[ $part =~ ^[A-Za-z0-9_][A-Za-z0-9._-]*$ ]] || { echo "invalid component"; return 1; }
  done
}
  • An absolute path such as /etc/passwd is rejected outright.
  • Because no component may start with a dot, .. and . can never appear, and neither can hidden folders like .git.
  • An empty component catches a//b and a trailing /. Rejecting these is stricter than the file system requires, but it keeps every accepted path in one simple, canonical form.
  • The pattern ^[A-Za-z0-9_][A-Za-z0-9._-]*$ combines the "no leading dot or hyphen" rule and the character allowlist in one regular expression: the first character must be a letter, digit or underscore.

IFS=/ read changes IFS only for that one read command. The check for control characters (shown in the complete example) runs first, so the here string cannot contain a newline that would cut the value short.

Resolving the Real Location with realpath

Text rules cannot see symbolic links, so the second layer asks the file system where a path really leads. realpath (GNU coreutils) prints the canonical absolute path: it removes . and .. components and follows every symbolic link.

OptionBehavior
realpath -eevery component must exist; fails otherwise
realpath -mnothing needs to exist; resolves as far as possible
(no option)all but the last component must exist
realpath -sdoes not follow symbolic links (only cleans up . and ..)

Run from /srv/t161:

path                                  -e                           -m                           -s -m
docs/guides/install.txt               /srv/t161/docs/guides/install.txt (same for all three)
docs/guides/../readme.txt             /srv/t161/docs/readme.txt (same for all three)
docs/guides/../../other/secret.txt    /srv/t161/other/secret.txt (same for all three)
docs/guides/escape.txt                /srv/t161/other/secret.txt  /srv/t161/other/secret.txt  /srv/t161/docs/guides/escape.txt
docs/outside/secret.txt               /srv/t161/other/secret.txt  /srv/t161/other/secret.txt  /srv/t161/docs/outside/secret.txt
docs/missing.txt                      No such file or directory   /srv/t161/docs/missing.txt  /srv/t161/docs/missing.txt

(docs/outside is a symbolic link to the folder /srv/t161/other.)

The important rows are the two symbolic links. With -e or -m, realpath shows that both lead to /srv/t161/other/secret.txt. With -s, the links are not followed and the paths still look as if they were inside docs. Never use -s for a security check. Use -e when the file must already exist (reading, deleting) and -m when it may not exist yet (creating), keeping in mind that with -m the missing parts are not checked at all.

Checking Containment

After resolving, compare the result with the resolved base folder:

base=$(realpath -e /srv/t161/docs)
for rel in guides/install.txt guides/../readme.txt guides/escape.txt ../docs-old/draft.txt; do
  t=$(realpath -m -- "$base/$rel")
  if [[ $t == "$base"/* ]]; then echo "inside : $rel -> ${t#"$base"/}"; else echo "outside: $rel -> $t"; fi
done
inside : guides/install.txt -> guides/install.txt
inside : guides/../readme.txt -> readme.txt
outside: guides/escape.txt -> /srv/t161/other/secret.txt
outside: ../docs-old/draft.txt -> /srv/t161/docs-old/draft.txt

Three details make this comparison correct:

  • Resolve the base folder too. If /srv/t161/docs were itself reached through a symbolic link, the resolved target would never start with the unresolved base text, and every check would fail (or, worse, a hand-written variant might pass the wrong paths).
  • Quote the base inside the pattern. In [[ $t == "$base"/* ]], the quotes make the base folder a literal string, so characters such as * or [ in a folder name are not treated as pattern characters.
  • Include the slash. Without it, a sibling folder whose name merely starts with the same text passes the check:
base=/srv/t161/docs
for p in /srv/t161/docs/readme.txt /srv/t161/docs-old/draft.txt /srv/t161/docs; do
  [[ $p == "$base"* ]]  && a=pass || a=fail
  [[ $p == "$base"/* ]] && b=pass || b=fail
  printf '%-30s  "$base"*: %s   "$base"/*: %s\n' "$p" "$a" "$b"
done
/srv/t161/docs/readme.txt       "$base"*: pass   "$base"/*: pass
/srv/t161/docs-old/draft.txt    "$base"*: pass   "$base"/*: fail
/srv/t161/docs                  "$base"*: pass   "$base"/*: fail

The "$base"/* form also rejects the base folder itself, which matters for commands that would act on the whole folder. realpath --relative-base=DIR offers a related check: it prints a path relative to DIR only when the path is inside DIR and prints it unchanged (absolute) otherwise.

Checking What Kind of File It Is

A path that is inside the base folder can still be the wrong type of file. Before using it, test for what the operation needs (lessons 71 and 72):

  • [[ -f $target ]] for a regular file to read. This rejects folders, devices such as /dev/zero and named pipes, which could make a reader block forever or read without end.
  • [[ -d $target && ! -L $path ]] for a folder you are about to write into. Testing -L on the unresolved path catches a folder that has been replaced by a symbolic link.
  • A size limit (stat -c %s) before reading a file into memory or sending it somewhere.

Time of Check and Time of Use

Every check above looks at the file system at one moment, and the script then uses the path a moment later. If another user can change the folders in between, for example by replacing a checked file with a symbolic link, the check no longer describes what is used. This gap is called a TOCTOU (time-of-check to time-of-use) race.

Shell scripts cannot close this gap completely, but they can make it small and harmless:

  • Keep the base folder writable only by the account that runs the script, so nobody else can plant links in it (see lesson 159).
  • Create new files in a way that fails if the name already exists, instead of checking first and writing second. Bash's set -C (noclobber) opens new files exclusively, and ln of a hard link fails if the target exists; both refuse a symbolic link planted under the target name.
  • Use the resolved path for the operation, not the original text, so the same location that was checked is the one that is used.

A Complete Example: A Document Store

docs.sh gives other programs, for example a small web handler, safe access to one base folder. get prints a document named by a relative path, put stores standard input under a new name in an inbox subfolder, and list lists the readable documents.

#!/usr/bin/env bash
# docs.sh: read and store documents inside one base folder
# usage: docs.sh get RELPATH   print a document from the base folder
#        docs.sh put NAME      store standard input as inbox/NAME
#        docs.sh list          list readable documents
set -euo pipefail
export LC_ALL=C

readonly BASE=${DOCS_BASE:-/srv/t161/docs}
readonly MAX_BYTES=1048576   # 1 MiB limit for get and put

tmp=''                       # upload temp file, removed on exit
trap '[[ -n $tmp ]] && rm -f -- "$tmp"' EXIT

die() { printf '%s: %s\n' "${0##*/}" "$1" >&2; exit 2; }

base_real=$(realpath -e -- "$BASE") || die "base folder missing: $BASE"

# check_text VALUE: rules that apply to every user-supplied path or name
check_text() {
  [[ -n $1 ]]                 || die 'empty path or name'
  (( ${#1} <= 255 ))          || die 'path or name longer than 255 bytes'
  [[ $1 != *[[:cntrl:]]* ]]   || die "control characters are not allowed: ${1@Q}"
}

# check_rel RELPATH: a relative path made of safe components
check_rel() {
  local p=$1 part
  local -a parts
  check_text "$p"
  [[ $p != /* ]] || die "absolute paths are not allowed: ${p@Q}"
  IFS=/ read -r -a parts <<< "$p"
  for part in "${parts[@]}"; do
    [[ -n $part ]]                     || die "empty path component: ${p@Q}"
    [[ $part != .* ]]                  || die "components must not start with a dot: ${p@Q}"
    [[ $part =~ ^[A-Za-z0-9_][A-Za-z0-9._-]*$ ]] \
                                       || die "invalid characters in ${part@Q}"
  done
}

# check_name NAME: a single file name, no folders
check_name() {
  check_text "$1"
  [[ $1 =~ ^[A-Za-z0-9_][A-Za-z0-9._-]*$ ]] \
    || die "invalid name ${1@Q}: use letters, digits, '.', '_' and '-', not starting with '.' or '-'"
  (( ${#1} <= 100 )) || die 'name longer than 100 characters'
}

cmd_get() {
  local rel=$1 target size
  check_rel "$rel"
  target=$(realpath -e -- "$base_real/$rel" 2>/dev/null) || die "no such document: ${rel@Q}"
  [[ $target == "$base_real"/* ]] || die "refusing ${rel@Q}: resolves outside the base folder"
  [[ -f $target ]]                || die "not a regular file: ${rel@Q}"
  size=$(stat -c %s -- "$target")
  (( size <= MAX_BYTES ))         || die "document too large: $size bytes"
  cat -- "$target"
}

cmd_put() {
  local name=$1 inbox size
  check_name "$name"
  inbox=$base_real/inbox
  mkdir -p -- "$inbox"
  [[ ! -L $inbox && -d $inbox ]] || die 'inbox is not a plain folder'
  tmp=$(mktemp -- "$inbox/.upload.XXXXXX")
  head -c "$((MAX_BYTES + 1))" > "$tmp"
  size=$(stat -c %s -- "$tmp")
  (( size <= MAX_BYTES )) || die "input larger than $MAX_BYTES bytes"
  chmod 640 -- "$tmp"
  # ln fails if the name already exists, so nothing is ever overwritten
  ln -- "$tmp" "$inbox/$name" 2>/dev/null || die "already exists: inbox/$name"
  printf 'stored inbox/%s (%d bytes)\n' "$name" "$size"
}

cmd_list() {
  find "$base_real" -type f ! -path '*/.*' -printf '%P\n' | sort
}

(( $# >= 1 )) || die 'usage: docs.sh get RELPATH | put NAME | list'
case $1 in
  get)  (( $# == 2 )) || die 'usage: docs.sh get RELPATH'; cmd_get "$2" ;;
  put)  (( $# == 2 )) || die 'usage: docs.sh put NAME';    cmd_put "$2" ;;
  list) (( $# == 1 )) || die 'usage: docs.sh list';        cmd_list ;;
  *)    die "unknown command: ${1@Q}" ;;
esac

How It Works

  • One base folder. BASE is resolved once with realpath -e into base_real, and every check compares against that resolved value. An environment variable can point the script at a test folder.
  • Shared text rules. check_text rejects empty values, values longer than 255 bytes (with LC_ALL=C, ${#1} counts bytes) and any control character. [[:cntrl:]] matches newline, tab, carriage return, the escape character and the other non-printing bytes.
  • Path rules for get. check_rel rejects absolute paths, empty components, components starting with a dot and components with characters outside the allowlist. Then realpath -e resolves the path, the containment test requires it to be strictly inside the base folder, -f requires a regular file and a size check limits what is printed.
  • Name rules for put. check_name allows only a single name, so put can never write outside inbox. The script also confirms that inbox is a real folder and not a symbolic link.
  • No overwriting. Input goes into a hidden temporary file created by mktemp inside inbox. head -c reads at most one byte more than the limit, so an oversized upload is detected without reading it all. ln then creates the final name as a hard link to the temporary file. ln fails if anything, including a planted symbolic link, already has that name, so existing files are never replaced. The EXIT trap removes the temporary name in every case.
  • Hidden files stay hidden. list skips any path containing a component that starts with a dot, which also hides the temporary upload files, and find without -L does not follow symbolic links, so escape.txt is not listed.

The first version of this script declared tmp as a local variable inside cmd_put and set the trap there. The trap runs when the script exits, after cmd_put has returned and its local variables are gone, so every successful upload failed with tmp: unbound variable under set -u and left its temporary file behind. Declaring tmp at the top of the script fixed both problems. Variables used by an EXIT trap must still exist when the script ends.

Running the Complete Example

Reading documents, including every attempt to leave the base folder:

for a in 'guides/install.txt' 'readme.txt' '../other/secret.txt' 'guides/../../other/secret.txt' \
         '/etc/passwd' 'guides/escape.txt' 'outside/secret.txt' '.env' '.git/config' \
         'guides//install.txt' 'guides' 'missing.txt' '-n' "$(printf 'readme.txt\nx')" ''; do
  printf '$ docs.sh get %q\n' "$a"; docs.sh get "$a"; echo "status $?"
done
$ docs.sh get guides/install.txt
Install steps
status 0
$ docs.sh get readme.txt
hello
status 0
$ docs.sh get ../other/secret.txt
docs.sh: components must not start with a dot: '../other/secret.txt'
status 2
$ docs.sh get guides/../../other/secret.txt
docs.sh: components must not start with a dot: 'guides/../../other/secret.txt'
status 2
$ docs.sh get /etc/passwd
docs.sh: absolute paths are not allowed: '/etc/passwd'
status 2
$ docs.sh get guides/escape.txt
docs.sh: refusing 'guides/escape.txt': resolves outside the base folder
status 2
$ docs.sh get outside/secret.txt
docs.sh: refusing 'outside/secret.txt': resolves outside the base folder
status 2
$ docs.sh get .env
docs.sh: components must not start with a dot: '.env'
status 2
$ docs.sh get .git/config
docs.sh: components must not start with a dot: '.git/config'
status 2
$ docs.sh get guides//install.txt
docs.sh: empty path component: 'guides//install.txt'
status 2
$ docs.sh get guides
docs.sh: not a regular file: 'guides'
status 2
$ docs.sh get missing.txt
docs.sh: no such document: 'missing.txt'
status 2
$ docs.sh get -n
docs.sh: invalid characters in '-n'
status 2
$ docs.sh get $'readme.txt\nx'
docs.sh: control characters are not allowed: $'readme.txt\nx'
status 2
$ docs.sh get ''
docs.sh: empty path or name
status 2

The .. paths, the absolute path and the hidden files were stopped by the text rules. The two symbolic links passed the text rules, because their names are ordinary, and were stopped by the containment check after realpath revealed where they lead. That is why both layers are needed.

Storing uploads:

echo "data for notes.txt" | docs.sh put notes.txt; echo "status $?"
echo "data for notes.txt" | docs.sh put notes.txt; echo "status $?"
echo "data for report-2026_11.md" | docs.sh put report-2026_11.md; echo "status $?"
head -c 2000000 /dev/zero | docs.sh put big.bin; echo "status $?"
ls -la docs/inbox
stored inbox/notes.txt (19 bytes)
status 0
docs.sh: already exists: inbox/notes.txt
status 2
stored inbox/report-2026_11.md (27 bytes)
status 0
docs.sh: input larger than 1048576 bytes
status 2
total 16
drwxr-xr-x 2 root root 4096 Nov 24 10:53 .
drwxr-xr-x 5 root root 4096 Nov 24 10:53 ..
-rw-r----- 1 root root   19 Nov 24 10:53 notes.txt
-rw-r----- 1 root root   27 Nov 24 10:53 report-2026_11.md

The second upload with the same name was refused instead of replacing the first, the oversized upload was refused, and no temporary files were left behind. Names such as ../evil.sh, .bashrc, -rf, a b.txt and sub/x.txt were all refused with the "invalid name" message.

Finally, an attacker who can replace the inbox folder with a symbolic link to another folder does not get a file written there, and listing shows only regular, non-hidden files inside the base folder:

echo x | docs.sh put planted.txt; echo "status $?"   # inbox is now a symlink to ../other
docs.sh list
docs.sh: inbox is not a plain folder
status 2
guides/install.txt
inbox/notes.txt
inbox/report-2026_11.md
readme.txt

(The list output above was taken after the real inbox folder was restored.)

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 Validating Paths and User-Supplied Filenames and get answers drawn from it.

Signed-in readers only.