Support Online
Skip to main content

Using Shell Script if else: Detailed Guide with Examples

When writing a shell script, not every command needs to run all the time.
The if-else structure gives decision making ability to your scripts.

In this guide, you will learn Bash if, else and elif structures with real scenarios.

What Will You Learn in This Guide?

  • basic if-else syntax
  • Numerical and textual comparisons
  • File and permission checks
  • use of elif and nested if
  • Automation scenarios

Technical Summary

This guide explains how to use Shell Script if else on Linux and Ubuntu systems.
The goal is to run automation scripts based on conditions.


Basic Logic of the if-else Structure

The basic structure in Bash is as follows:

if [ koşul ]; then
komutlar_1
else
komutlar_2
fi
  • This construct runs different code if the condition is true or false.

⚠️ Note:

  • space inside is mandatory. Bash is case sensitive.

  • Most Frequently Used Condition Operators

ConditionDescription
[ $a -eq $b ]Are the numbers equal
[ $a -gt $b ]Is a greater than b
[ $a -lt $b ]Is a less than b
[ -f dosya ]Is there a file
[ -r dosya ]Is the file readable
[ -z "$var" ]Is the variable empty

1. Comparing Two Numbers


#!/bin/bash
m=10
n=20

if [ $n -eq $m ]; then
echo "Sayılar eşit"
else
echo "Sayılar farklı"
fi
  • This script checks numerical equality.

2. File and Read Permission Control (Nested if)


#!/bin/bash
dosya="/home/genixnode/ayarlar.conf"

if [ -f "$dosya" ]; then
if [ -r "$dosya" ]; then
echo "Dosya mevcut ve okunabilir"
else
echo "Dosya var ama okuma izni yok"
fi
else
echo "Dosya bulunamadı"
fi
  • This structure is frequently used in security and configuration controls.

3. Using elif for Multiple Conditions


#!/bin/bash
puan=85

if [ $puan -ge 90 ]; then
echo "Derece: A"
elif [ $puan -ge 80 ]; then
echo "Derece: B"
else
echo "Derece: C veya altı"
fi
  • elif simplifies code in multiple decision scenarios.

Frequently Asked Questions (FAQ)

1. What is the difference between == and -eq? == makes a text comparison, -eq makes a numerical comparison.

2. Why are square brackets important? [ is a command. If there is no space, it gives an error.

3. How to write multiple conditions? && (and), || (or) operators are used.

4. What can I use instead of if? The case structure is recommended in cases with multiple options.


Result

if-else is the basic building block of Shell Script. When used correctly, automation works safer and smarter.

You can speed up your processes by using these scripts on your GenixNode servers 🚀