Conditional Tests and Logic
Demonstrates if/elif/else conditionals with test commands, file tests, string tests, numeric comparisons, and logical operators in Bash scripts.
Code
#!/usr/bin/env bash
set -euo pipefail
file="${1:-}"
num=42
# File tests
if [[ -f "$file" ]]; then
echo "Regular file: $file"
elif [[ -d "$file" ]]; then
echo "Directory: $file"
elif [[ -e "$file" ]]; then
echo "Exists but unknown type"
else
echo "Does not exist: $file"
fi
# Numeric comparisons
if (( num > 50 )); then
echo "Greater than 50"
elif (( num == 42 )); then
echo "The answer to everything"
else
echo "Less than 42"
fi
# String tests
str="hello"
if [[ -n "$str" && "$str" == h* ]]; then
echo "Non-empty string starting with h"
fi
# Logical operators
if [[ -r "$file" && -w "$file" ]]; then
echo "File is readable and writable"
fi
# Ternary-like assignment
result=$(( num % 2 == 0 ? 1 : 0 ))
echo "Is even: $result"How it works
set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.
The script leans on parameter expansion 1 time, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.
The key statements, annotated
if (( num > 50 )); then
echo "Greater than 50"
result=$(( num % 2 == 0 ? 1 : 0 ))
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Report a problem with this exampleOpens a pre-filled issue on GitHub.