Bash Test Patterns Real Scripts Actually Use
In this article
The most common test patterns in real-world bash scripts are the [[ ... ]] conditional for string and file comparisons, the -f, -d, and -x file operators, and the &&/|| short-circuit chains for quick checks. These patterns appear in nearly every production script because they are portable, readable, and handle the edge cases that naive test or [ ... ] usage often misses.
Why the Test Pattern Matters
Bash scripting is mostly about making decisions: is a file present, does a variable have a value, is a command successful? The test pattern is the syntax you use to ask those questions. A wrong test can silently skip a critical step, overwrite a file, or run a command with an empty argument. Real scripts use a small set of proven patterns because they are reliable across different systems and shell versions.
The Core Syntax: [[ ]] vs [ ] vs test
Bash offers three ways to write a test: test expression, [ expression ], and [[ expression ]]. The first two are equivalent (the [ is actually a command, not syntax), but [[ ]] is a bash keyword that parses its contents differently. Real scripts almost always use [[ ]] because it avoids word-splitting and pathname expansion, supports pattern matching with == and =~, and handles empty variables gracefully. For POSIX sh compatibility, you must use [ ] or test, but most modern systems run bash as the default shell.
File Tests: The Workhorse of Scripts
The most common file test operators are:
-e file– true if the file exists (any type)-f file– true if it is a regular file (not a directory or device)-d file– true if it is a directory-r file,-w file,-x file– true if the file is readable, writable, or executable by the current user-s file– true if the file exists and is not empty-L file– true if the file is a symbolic link
For example, a backup script might check if [[ -d "$BACKUP_DIR" ]]; then before writing there, and a deployment script might check if [[ -x "./deploy.sh" ]]; then to ensure the script is executable. These tests are cheap and fast, so they are used liberally.
String and Variable Tests
Checking whether a variable is set or non-empty is another staple. The classic pattern is:
if [[ -n "$VAR" ]]; then
echo "VAR is set and not empty"
else
echo "VAR is unset or empty"
fiThe -n operator returns true if the string length is non-zero; -z returns true if it is zero. Real scripts also use ${VAR:-default} to substitute a default value when a variable is unset or empty, which is a form of test in itself. For comparing strings, use == (or = for POSIX) and !=. Note that [[ "$a" == "$b" ]] is safe even if $a or $b contains spaces or wildcards because the right side is treated as a pattern unless quoted.
Command Success and Short-Circuiting
Scripts often need to check whether a command succeeded. The exit status $? is 0 for success, non-zero for failure. The idiomatic way is to use if command; then directly, or to chain commands with && (run next only if previous succeeds) and || (run next only if previous fails). For example:
mkdir -p "$OUTPUT" || { echo "Failed to create directory" >&2; exit 1; }This pattern is everywhere in real scripts because it is concise and clearly expresses the intent. However, be careful with set -e (exit on error): it can cause unexpected exits when a command fails in a conditional context. Many scripts use set -euo pipefail to catch errors early, but then they must use if or || to handle expected failures.
Common Mistakes and Pitfalls
Even experienced scripters hit these traps:
- Forgetting to quote variables –
[[ -f $file ]]breaks if$filecontains spaces. Always quote:[[ -f "$file" ]]. - Using
=instead of==for string equality in[[ ]]– both work in bash, but==is clearer. - Mixing up
-a/-owith&&/||– inside[[ ]], use&&and||; inside[ ], use-aand-o(but they are deprecated). - Testing for a directory with
-f–-fis for regular files, not directories. - Using
[[ -e "$file" ]]when you really need-for-d–-ematches any type, including broken symlinks (which are actually false for-ein some shells, but true for-L).
How to Choose the Right Test
The choice depends on what you are checking and what shell you target. If you are writing a bash script (shebang #!/bin/bash), use [[ ]] for all conditionals. If you need POSIX compliance (e.g., for sh on some systems), stick to [ ] and avoid ==, use = instead. For file checks, think about the type: -f for regular files, -d for directories, -e for “exists” when you do not care about type. For command success, use if command; then or command || handle_failure.
Frequently Asked Questions
What is the difference between [[ ]] and [ ]?
[[ ]] is a bash keyword that does not perform word-splitting or pathname expansion on its arguments, so you can write [[ $var == "a b" ]] without quoting $var (though quoting is still recommended). It also supports == for pattern matching and =~ for regex. [ ] is an external command (or builtin) that follows POSIX rules, requires spaces around the brackets, and treats > and < as redirection operators unless escaped.
Why does [[ -e "$file" ]] return true for a broken symlink?
Actually, -e returns false for a broken symlink in most shells because the target does not exist. To test for a symlink itself, use -L. If you want to check whether the symlink target exists, use -e on the symlink path, but be aware that it follows the link.
How do I test if a variable is a number?
Bash does not have a built-in numeric test, but you can use a regex: [[ "$var" =~ ^[0-9]+$ ]] for positive integers. For decimals, use ^[0-9]+([.][0-9]+)?$. Alternatively, use case or printf tricks, but regex is the most common.
What does set -e do and why does it cause problems with tests?
set -e makes the script exit immediately if any command returns a non-zero status. This can be dangerous in conditionals because a command like grep that returns 1 when no match is found would exit the script. The workaround is to use if grep ...; then or append || true to the command. Many scripts use set -e but then carefully write conditionals to avoid unexpected exits.
Is there a difference between test and [?
No, test and [ are the same command; [ is just a synonym that requires a closing ]. In bash, both are builtins, but they behave identically to the external /usr/bin/test and /usr/bin/[.
How do I check if a command exists in the PATH?
Use command -v or type in a conditional: if command -v "$cmd" >/dev/null; then. The command -v prints the path if found, and redirecting output to /dev/null suppresses it.