Skip to content

Bash Scripting

Terminal window
if [[ condition ]]; then
commands
elif [[ condition ]]; then
commands
else
commands
fi

Three test constructs exist, with important differences:

Feature[ ] (POSIX test)[[ ]] (bash)
Word splittingYes (quote vars)No
Glob expansionYesNo
Pattern matchingNoYes (==``!=)
Regex matchingNoYes (=~)
Logical operators-a``-o&&``||
Empty string safetyRequires quotingSafe without quotes
Terminal window
# POSIX test — requires quoting
[ -f "$file" ] && echo "exists"
[ "$var" = "value" ]
[ "$n" -eq 5 ]
# Bash test — no quoting required for most cases
[[ -f $file ]] && echo "exists"
[[ $var == "value" ]]
[[ $n -eq 5 ]]
# Pattern matching with [[ ]]
if [[ $filename == *.log ]]; then
echo "Log file"
fi
# Regex matching with [[ ]]
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
echo "Valid IPv4 format"
fi