MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Shell Scripting Tutorials: Conditional statatement using if

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


Two bash if elif else fi syntax styles, noting required spaces inside square brackets

Flowchart of a bash if-else statement running Statement 1 when true and Statement 2 when false

Flowchart of nested bash if statements checking conditions 1 to 3 before continuing the program

Bash script comparing

Here are some useful examples of if-else in shell scripts to give you a better idea of how to use this tool.

CommandDescription
&&Logical AND
$0Argument 0 i.e. the command thatโ€™s used to run the script
$1First argument (change number to access further arguments)
-eqEquality check
-neInequality check
-ltLess Than
-leLess Than or Equal
-gtGreater Than
-geGreater 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:

SyntaxTypeBest used for
[ ... ]POSIX command (test)Portable scripts that may run under /bin/sh
[[ ... ]]Bash keywordString, pattern and regex tests in bash scripts. Safer with unquoted variables
(( ... ))Bash arithmeticNumeric 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:

OperatorCategoryTrue when
-eq, -neIntegerEqual / not equal
-lt, -le, -gt, -geIntegerLess than, less or equal, greater than, greater or equal
= (or == in [[ ]])StringStrings are identical
!=StringStrings differ
-z "$s"StringString is empty
-n "$s"StringString is not empty
-e fileFilePath exists
-f fileFilePath is a regular file
-d dirFilePath is a directory
-r, -w, -xFilePath is readable / writable / executable
-s fileFileFile exists and is not empty
!LogicNegates 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 symptomCauseFix
[condition]: command not found or [1: command not foundNo space after [ or before ]Write [ condition ] with spaces on both sides
Condition is always trueNo spaces around = or ==, so the test sees one non-empty string[ "$a" = "$b" ]
[: -gt: unary operator expectedVariable is empty and unquoted, so an operand disappearsQuote variables ("$a") or use [[ ]]
integer expression expectedNon-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 fileAn if without a closing fi (or case without esac)Match every if with fi
[[: not foundScript runs under sh/dash, not bashUse #!/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 POSIX sh.
  • Use read -rp "Prompt: " var instead of echo -e "...\c" followed by read. Add -s for 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 case instead of long elif chains 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals

Related Posts

Shell Bash Scripting: Assignment & Excercise โ€“ 16

This exercise asks for a Bash script that packs a file or directory into a compressed tar archive and then encrypts it with a passphrase. The solution…

Read More

Shell Bash Scripting: Assignment & Excercise โ€“ 15

This exercise builds a Bash script that takes an IP address, sends it to the free ip-api.com geolocation API with curl, and uses jq to print the…

Read More

Shell script to git add and commit and push each directory at a time

This page shows how to use a Bash script to stage, commit and push changes one directory at a time. That can mean a folder full of…

Read More

AWS Tutorials: AWS CodeBuild – Buildspec code for creating AMI from running instances

This page has an AWS CodeBuild buildspec that finds every running EC2 instance tagged environment=uat and creates an AMI from each one with the AWS CLI. It…

Read More

Shell Bash Scripting: Assignment & Excercise – 7

This exercise uses Bash, rsync and SSH to copy a local file to a remote backup server, then sends an email when the copy finishes. Below the…

Read More

Shell Bash Scripting: Assignment & Excercise – 4

This exercise asks for a Bash script that checks CPU usage and sends an email when it goes over a threshold. The script above reads /proc/stat, but…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x