Pcornel
Browse topics
Options
Recent
Favorites
Automation · Technical reference

Conditions · Bash Automation

Direct answer

Bash conditions use if with [[ ]] for tests on strings, numbers and files, such as [[ -f $file ]] or [[ $n -gt 5 ]], plus case for matching patterns.

When to use this

Use this when writing if and case logic in Bash.

First 30 seconds

1. Use [[ ]] for tests, (( )) for numbers.

2. Check command success with if cmd; then.

3. Quote in [ ].

4. case for multiple patterns.

5. Handle else branches.

Operational verification

condition → branch

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
GNU Bash 5.3/current
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformGNU Bash 5.3/current · Automation implementations are tool and platform specific. Use the adjacent Domain for the technology being automated and this Domain for automation behavior.
Scope / prerequisiteUse this when writing if and case logic in Bash.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Verification path Verify boundary

Verification should show both parser correctness and branch behavior. Run bash -n first so syntax errors are separated from runtime decisions, then execute a compact input matrix that deliberately enters every meaningful branch. When a branch is driven by an external command, capture that command's numeric status immediately and compare it with the expected contract; do not infer the status from its human-readable output. set -x or a scoped PS4 trace can show which branch was reached, but the trace is supporting evidence rather than the final evidence of the actual state. For [[ ... =~ ... ]], inspect BASH_REMATCH only after a successful match and include cases that intentionally do not match. After the branch action runs, verify the consumer-visible target state independently so the test shows more than 'the if statement evaluated true'. Keep the input, evaluator form, observed status, selected branch, and read-back together in the evidence.

Step 2 Common mistakes Narrow the fault
  • [ $x = y ] failing when $x is empty (quote it or use [[ ]]).
Step 3 Where it fails Narrow the fault

The first boundary is parsing: malformed [[, [, or arithmetic syntax is not a false condition. The second is expansion and type semantics: an unset variable, glob pattern, regex, numeric conversion, or locale-sensitive comparison can produce a valid but unintended predicate. The third is the command-status boundary: an external probe can fail because its dependency is unavailable, which is different from the business condition being false. Finally, a correctly selected branch can still fail while changing the target. Do not collapse those layers into 'the condition failed'. Preserve the expression form, expanded inputs, predicate status, selected branch, and post-action read-back separately. A remediation should change the earliest failing step—input contract, predicate implementation, dependency, or action—not simply invert the branch. Re-run the original automation input after correction to show the intended decision path and resulting state.

Evidence references

Evidence · 1 on this Topic

Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.

observation · 1
Key points
  • Use [[ ]] for tests.
  • -f file, -d dir, -z empty, -eq numbers.
  • case for pattern matching.
Key checks
  • [[ -n "$var" ]] && echo set — string test
  • [[ -f /path ]] — file test
  • (( count > 5 )) — arithmetic test
ReferenceWhy it matters1 section · depth on demand

In depth

Bash conditions use if, case and the test constructs [[ ]] (strings/files) and (( )) (arithmetic). The condition is simply a command whose exit code 0 means true.

if [[ -z "${1:-}" ]]; then echo "usage: $0 host" >&2; exit 2; fi
if (( free_gb < 5 )); then echo "low disk"; fi
if grep -q 'PermitRootLogin yes' /etc/ssh/sshd_config; then echo insecure; fi
case "$env" in
  prod) target=10.0.0.10 ;;
  lab)  target=10.9.0.10 ;;
  *)    echo "unknown env" >&2; exit 2 ;;
esac
TestMeaning
-f / -dFile / directory exists
-z / -nString empty / not empty
==, =~String equal / regex match
ReferenceImportant terms & boundaries1 section · depth on demand

Mechanics

Bash conditions are primarily exit-status decisions. if, while, until, &&, and || consume the status returned by a command or compound command; zero means success/true and non-zero means failure/false. [ is a command with its own parsing rules, [[ ... ]] is a Bash conditional construct that avoids normal word splitting and pathname expansion for its operands, and (( ... )) evaluates arithmetic where a non-zero arithmetic value yields a successful condition. Pattern matching inside [[ ]], regular-expression matching with =~, and short-circuit list operators each have different expansion and quoting semantics. A robust Bash Automation condition therefore begins by identifying which evaluator owns the expression and which status it returns, rather than treating every-looking boolean expression as the same language. Locale, shell options such as nocasematch, and whether a command appears in a pipeline can also change the effective decision boundary.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
ReferenceConfiguration & state1 section · depth on demand

Lifecycle

Author conditions so the branch contract survives non-interactive execution. Prefer [[ ... ]] for Bash-specific string/file tests when portability to POSIX sh is not required, quote expansions when they leave [[ ]], and make empty/unset input behavior explicit with parameter expansion such as ${name:-} or a precondition check. Keep side effects out of condition expressions unless the side effect is the intended test, because retries or diagnostic re-runs can otherwise mutate state. For automation, test positive, negative, empty, malformed, and boundary-value inputs before release, and document any dependence on locale, globbing, regex syntax, or external command exit codes. Treat set -e as execution policy rather than as a substitute for explicit condition handling; its exceptions around condition lists and compound commands are context-sensitive. A change to condition logic should be reviewed with the same care as a change to the action it gates.

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docGNU Bash 5.3/current 5.3/current

Authoritative/upstream documentation reviewed for bounded claims in Bash Automation > Conditions. Documentation verification only; this is not observed lab or production Evidence.

Basis: https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html · confidence 94%
Embedded reference data

Quick lookup tables

Bash Automation → Conditions · operational reference

Context-specific ownership, verification, output and failure-boundary lookup for Bash Automation → Conditions.

LayerBash Automation → Conditions operational reference
Context identityGNU Bash 5.3/current + exact revision/input/target identity
Persistent intentVersioned contract/configuration with explicit ownership and prerequisites
VerificationValidate inputs/read current state → exercise bounded operation → independent target read-back
Output contractPreserve structured status/IDs/properties before human formatting
Failure boundarySeparate source/input/engine/controller execution from downstream target outcome
Depth when you need it

Deep reference

Healthy vs suspicious evidence

Output interpretation

Condition output has two different channels: the condition's exit status controls flow, while anything written to stdout/stderr is ordinary data. [[ ... ]], (( ... )), and many test expressions normally produce no useful stdout, so a blank terminal is not evidence that a condition was false. External predicates may emit diagnostic text while still returning a status that is the actual branch signal. When debugging, record the exact status and the values after expansion, preferably with safe quoting such as printf '%q', instead of copying only an xtrace line whose formatting can be ambiguous. For regex conditions, BASH_REMATCH is transient state and should be consumed before a later match overwrites it. In automation logs, distinguish 'predicate result', 'selected branch', and 'action outcome' so a downstream failure is not misreported as a condition failure. This separation makes repeated runs and post-incident comparison materially easier.

Confirmation

Confirm action

Continue?