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"Report a problem with this exampleOpens a pre-filled issue on GitHub.