Bash makes decisions with if, if-else, if-elif-else, nested if and case. Each one runs a command or test and branches on its exit status. Below the original examples you'll find how conditions are actually evaluated, the operators you'll use most, corrected versions of the scripts that contain bugs, and fixes for the errors beginners usually hit.
Conditional Statements: There are total 5 conditional statements which can be used in bash programming
if statement
if-else statement
if..elif..else..fi statement (Else If ladder)
if..then..else..if..then..fi..fi..(Nested if)
switch statement




Here are some useful examples of if-else in shell scripts to give you a better idea of how to use this tool.
| Command | Description |
| && | Logical AND |
| $0 | Argument 0 i.e. the command thatโs used to run the script |
| $1 | First argument (change number to access further arguments) |
| -eq | Equality check |
| -ne | Inequality check |
| -lt | Less Than |
| -le | Less Than or Equal |
| -gt | Greater Than |
| -ge | Greater Than or Equal |
How a bash if statement really works
In bash, if doesn't evaluate a boolean expression the way it does in Python or Java. It runs a command and checks its exit status. An exit status of 0 counts as true, and anything else counts as false. [ is itself a command (also called test), which is why the spaces around it are required.
# Any command can be a condition
if grep -q '^root:' /etc/passwd; then
echo "root user exists"
fi
# [ is a command: these two lines are equivalent
[ 5 -gt 3 ] && echo "true"
test 5 -gt 3 && echo "true"
# See the exit status directly
[ 5 -gt 3 ]; echo $? # prints 0 (true)
[ 3 -gt 5 ]; echo $? # prints 1 (false)Code language: PHP (php)
Bash gives you three ways to write a test. You'll see all three in real scripts:
| Syntax | Type | Best used for |
|---|---|---|
[ ... ] | POSIX command (test) | Portable scripts that may run under /bin/sh |
[[ ... ]] | Bash keyword | String, pattern and regex tests in bash scripts. Safer with unquoted variables |
(( ... )) | Bash arithmetic | Numeric comparisons using <, >, ==, % |
Syntax of each conditional form
The list above names five forms. Bash has no switch keyword. It uses case instead. Here is the correct syntax for each form:
# 1. if
if [ condition ]; then
commands
fi
# 2. if-else
if [ condition ]; then
commands
else
other_commands
fi
# 3. if-elif-else (else-if ladder)
if [ condition1 ]; then
commands
elif [ condition2 ]; then
commands
else
commands
fi
# 4. Nested if
if [ condition1 ]; then
if [ condition2 ]; then
commands
fi
fi
# 5. case (the bash equivalent of switch)
case "$variable" in
pattern1) commands ;;
pattern2|pattern3) commands ;;
*) default_commands ;;
esacCode language: PHP (php)
A practical case example, the kind of check found in deployment scripts:
#!/bin/bash
read -rp "Enter environment (dev/stage/prod): " env
case "$env" in
dev|development) echo "Deploying to development" ;;
stage) echo "Deploying to staging" ;;
prod) echo "Deploying to production" ;;
*) echo "Unknown environment: $env" >&2; exit 1 ;;
esacCode language: PHP (php)
Corrected versions of the example scripts
Several scripts in the gist above run without any error but give wrong results. The most serious bug is in Program 4 and Program 5. Writing [ $((n%2))==0 ] or [ $pass="password" ] with no spaces around the operator gives [ a single non-empty string, and [ always treats a non-empty string as true. So every number is reported as even and every password is accepted.
# Demonstrating the bug
n=7
if [ $((n%2))==0 ]; then echo "even"; fi # prints "even" - wrong!
# Program 4 - corrected
#!/bin/bash
n=10
if [ $((n % 2)) -eq 0 ]; then
echo "The number is even."
else
echo "The number is odd."
fi
# Same check with bash arithmetic
if (( n % 2 == 0 )); then echo "even"; else echo "odd"; fiCode language: PHP (php)
# Program 5 - corrected
#!/bin/bash
read -rsp "Enter password: " pass # -s hides input, -p shows the prompt
echo
if [ "$pass" = "password" ]; then
echo "The password is correct."
else
echo "The password is incorrect, try again."
fiCode language: PHP (php)
Note: Program 5 is only a teaching example. Never hardcode real credentials in a script. Use a secrets manager or environment variables, and don't echo secrets to the terminal or to logs.
Programs 3 and 7 print a misleading message when the two values are equal. Program 3 says a is greater because it uses -ge. Program 7 says b is greater. Add an explicit branch for equality:
#!/bin/bash
read -rp "Enter first value: " a
read -rp "Enter second value: " b
if [ "$a" -gt "$b" ]; then
echo "$a is greater than $b"
elif [ "$a" -lt "$b" ]; then
echo "$b is greater than $a"
else
echo "Both values are equal"
fiCode language: PHP (php)
Program 9 (nested if) works, but you can modernise it. Use $(( )) instead of backticks with expr, use && instead of the obsolescent -a, and validate the input first. Because each elif only runs when the earlier conditions failed, the upper-bound checks such as -lt 75 aren't needed:
#!/bin/bash
# Purpose: Validate and report student subject marks
read -rp "Maths marks: " m
read -rp "Physics marks: " p
read -rp "Chemistry marks: " c
for v in "$m" "$p" "$c"; do
if [[ ! $v =~ ^[0-9]+$ ]]; then
echo "Invalid input: '$v' is not a whole number" >&2
exit 1
fi
done
if (( m >= 35 && p >= 35 && c >= 35 )); then
total=$(( m + p + c ))
avg=$(( total / 3 )) # integer division
echo "Total Marks = $total"
echo "Average Marks = $avg"
if (( avg >= 75 )); then
echo "Congrats, you got Distinction"
elif (( avg >= 60 )); then
echo "Congrats, you got First Class"
elif (( avg >= 50 )); then
echo "You got Second Class"
else
echo "You got Third Class"
fi
else
echo "Sorry, you failed"
fiCode language: PHP (php)
Example run: entering 80, 70 and 75 prints Total Marks = 225, Average Marks = 75 and Congrats, you got Distinction.
Test operators you will use most
The table in the original lists only the integer operators. String and file tests come up just as often in DevOps scripts:
| Operator | Category | True when |
|---|---|---|
-eq, -ne | Integer | Equal / not equal |
-lt, -le, -gt, -ge | Integer | Less than, less or equal, greater than, greater or equal |
= (or == in [[ ]]) | String | Strings are identical |
!= | String | Strings differ |
-z "$s" | String | String is empty |
-n "$s" | String | String is not empty |
-e file | File | Path exists |
-f file | File | Path is a regular file |
-d dir | File | Path is a directory |
-r, -w, -x | File | Path is readable / writable / executable |
-s file | File | File exists and is not empty |
! | Logic | Negates the test, e.g. [ ! -d /backup ] |
#!/bin/bash
config=/etc/myapp/app.conf
if [ ! -f "$config" ]; then
echo "Config file $config not found" >&2
exit 1
fi
if [ -z "$APP_ENV" ]; then
echo "APP_ENV is not set, defaulting to dev"
APP_ENV=dev
fiCode language: PHP (php)
Combining conditions with && and ||
The original scripts join tests with -a (AND). POSIX marks -a and -o as obsolescent because they can be ambiguous. Use one of these forms instead:
# Separate [ ] tests joined by shell operators (portable)
if [ "$a" -gt "$b" ] && [ "$a" -gt "$c" ]; then echo "a is biggest"; fi
# Inside [[ ]] (bash)
if [[ $user == admin || $user == root ]]; then echo "privileged"; fi
# Inside (( )) for arithmetic (bash)
if (( a > b && a > c )); then echo "a is biggest"; fiCode language: PHP (php)
Note: Inside [[ ]], < and > compare strings alphabetically, not numerically. [[ 10 > 9 ]] is false because "1" sorts before "9". For numbers, use -gt or (( 10 > 9 )).
Common errors and how to fix them
| Error or symptom | Cause | Fix |
|---|---|---|
[condition]: command not found or [1: command not found | No space after [ or before ] | Write [ condition ] with spaces on both sides |
| Condition is always true | No spaces around = or ==, so the test sees one non-empty string | [ "$a" = "$b" ] |
[: -gt: unary operator expected | Variable is empty and unquoted, so an operand disappears | Quote variables ("$a") or use [[ ]] |
integer expression expected | Non-numeric value used with -eq, -gt etc. | Validate input with [[ $v =~ ^[0-9]+$ ]] first |
syntax error near unexpected token 'fi' | Missing then, or then on the same line without ; | if [ x ]; then or put then on its own line |
syntax error: unexpected end of file | An if without a closing fi (or case without esac) | Match every if with fi |
[[: not found | Script runs under sh/dash, not bash | Use #!/bin/bash and run with bash script.sh or ./script.sh |
The gist puts several programs in one file. A #!/bin/bash line only works as a shebang when it is the very first line of a script. Save each program as its own file, make it executable with chmod +x file.sh, and run it with ./file.sh.
Best practices for conditionals in scripts
- Quote variables inside
[ ]:"$var". Unquoted variables break when they are empty or contain spaces. - Prefer
[[ ]]and(( ))in bash-only scripts. Use[ ]when the script must run under POSIXsh. - Use
read -rp "Prompt: " varinstead ofecho -e "...\c"followed byread. Add-sfor secrets. - Validate user input before any numeric comparison.
- Send error messages to stderr (
>&2) and exit with a non-zero status so CI pipelines detect failures. - Use
caseinstead of longelifchains when you are matching one variable against fixed values or patterns. - Run a linter such as ShellCheck on your scripts. It flags missing quotes and the
[ $a==$b ]bug shown above.
To practise, try the Shell Bash Scripting assignment 3 or browse more Shell Scripting tutorials.
Frequently asked questions
What is the difference between [ ] and [[ ]] in bash?
[ ] is the POSIX test command, so it works in any shell. Variables inside it must be quoted. [[ ]] is a bash keyword: it doesn't word-split variables, and it supports &&, ||, glob patterns with == and regex matching with =~.
Why does my bash if statement always evaluate to true?
The usual cause is a missing space around the comparison operator, as in [ $a==$b ]. Bash then sees one non-empty string, which is always true. Write [ "$a" = "$b" ] with spaces on both sides of the operator.
Does bash have a switch statement?
No. Bash uses case ... in ... esac. Each branch ends with ;; and *) acts as the default branch.
How do I check if a file or directory exists in bash?
Use [ -f "$path" ] for a regular file, [ -d "$path" ] for a directory, and [ -e "$path" ] for any kind of path. Put ! in front to test that it does not exist, for example [ ! -d /backup ].
What does 'unary operator expected' mean in bash?
A variable in your test was empty and unquoted, so [ received an operator with only one operand, for example [ -eq 5 ]. Quote the variable ([ "$x" -eq 5 ]) or switch to [[ ]].
Related tutorials
- What is Bash and use cases of Bash?
- Shell Bash Scripting Interview Questions and Answer โ Part 4
- Shell Bash Scripting: Assignment & Excercise โ 3
- More Shell Scripting tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals