Paperlive
HOME / BLOG / VARIABLES, LOOPS AND CONDITIONS IN SHELL SCRIPTING EXPLAINED

Variables, Loops and Conditions in Shell Scripting Explained

Variables, Loops and Conditions in Shell Scripting Explained

What is Shell Scripting?

Shell scripting is when you write a series of commands for the shell to execute automatically. Shell scripts are written in languages like Bash. They help system tasks, CI/CD pipelines, server configuration and DevOps workflows.

Before you start with scripting loops and conditions you need to understand the three parts that make shell scripts powerful:

  • Variables store and reuse data.
  • Conditions make decisions based on logic.
  • Loops repeat actions efficiently.

Who should read this? System administrators, developers and DevOps engineers who want to write automation scripts in Bash.

Variables in Shell Scripting

Variables in shell scripting allow you to store values and reuse them throughout your script. They are like the memory of your script.

To declare a variable in Bash simply assign a value. For example:

NAME="DevOps Engineer"

VERSION="2.0"

echo "Hello, $NAME. Running version $VERSION"

Remember, do not leave spaces around the = sign. Writing NAME = "value" will cause an error.

Environment Variables

Environment variables are available to all processes. Some common ones include:

  • $HOME – The users home directory
  • $USER – The logged-in username
  • $PATH – The directories searched for commands
  • $PWD – The working directory
  • $SHELL – The default shell path

You can store the output of a command inside a variable using $(). For example:

TODAY=$(date +%Y-%m-%d)

echo "Todays date is: $TODAY"

Read-Only and Unset Variables

You can make a variable read-only or unset it. For example:

readonly PI=3.14159

unset NAME

Ready to become a DevOps engineer?
Industry-certified DevOps training online · 100% job-opportunity guarantee
Get Curriculum →

Conditions in Shell Scripting

Condition statements allow your shell script to make decisions. They evaluate expressions and branch execution accordingly.

The if syntax is used to evaluate conditions. For example:

if [ condition ]; then

    # block executed if condition is true

elif [ other_condition ]; then

    # block executed if other_condition is true

else

    # block executed if all conditions are false

fi

Real-World Example: Checking a File

For example you can check if a file exists:

FILE="/etc/hosts"

if [ -f "$FILE" ]; then

    echo "$FILE exists and is a regular file."

elif [ -d "$FILE" ]; then

    echo "$FILE is a directory."

else

    echo "$FILE does not exist."

fi

Common Conditional Operators

Some common conditional operators include:

  • -eq Equal to (numeric)
  • -ne Not equal to (numeric)
  • -lt Less than
  • -gt Greater than
  • = String equal
  • -f File is regular
  • -d Directory exists
  • -z String is empty

case Statement

The case statement is a way to evaluate multiple conditions:

DAY="Monday"

case "$DAY" in

    "Monday") echo "Start of the work week" ;;

    "Friday") echo "Almost the weekend!" ;;

    "Saturday"|"Sunday") echo "Weekend!" ;;

    *) echo "Midweek day" ;;

esac

Shell Scripting Loops

Shell scripting loops are really useful tools in automation. They let you do things over and over like looking at files, checking on services and doing tasks without having to write the same code multiple times.

Bash has three kinds of loops: for, while and until.

The for Loop

The for loop goes through a list of things or a range of numbers. Here are some examples:

for FRUIT in apple banana cherry; do

    echo "Fruit: $FRUIT"

done

for i in {1..5}; do

    echo "Count: $i"

done

The while Loop

The while loop keeps going as long as something is true. It is great for checking on things, reading files line by line or waiting for something to happen:

COUNT=1

while [ $COUNT -le 5 ]; do

    echo "Iteration: $COUNT"

    COUNT=$(( COUNT + 1 ))

done

The until Loop

The until loop is the opposite of the while loop. It keeps going until something becomes true:

COUNT=1

until [ $COUNT -gt 5 ]; do

    echo "Still going: $COUNT"

    COUNT=$(( COUNT + 1 ))

done

Combining Variables, Loops & Conditions

The real power of scripting loops comes when you use them with variables and conditions. Here is a useful script that checks how much space is used on a disk and sends an alert:

#!/bin/bash

THRESHOLD=80

PARTITIONS=$(df -h | awk 'NR>1 {print $5, $6}')

while IFS= read -r LINE; do

    USAGE=$(echo "$LINE" | awk '{print $1}' | tr -d '%')

    MOUNT=$(echo "$LINE" | awk '{print $2}')

    if [ "$USAGE" -ge "$THRESHOLD" ]; then

        echo "ALERT: $MOUNT is at ${USAGE}% usage!"

    else

        echo "OK: $MOUNT is at ${USAGE}% usage."

    fi

done <<< "$PARTITIONS"

This matters in DevOps because scripts like this one are used to monitor infrastructure. Understanding shell scripting loops, variables and conditions is a skill for anyone working with Linux servers, CI/CD pipelines or cloud infrastructure.

Want to Master Shell Scripting & DevOps?

This blog covers the basics. There is a lot more to learn. If you want to build a career in DevOps, hands-on training makes a difference.

Sign up for our DevOps Course. Go from scripting basics to production-ready automation with expert guidance and real-world projects.

DevOps Course: https://paperlive.in/devops-training-online

FAQs

Q1. What are the three types of scripting loops in Bash?

A. Bash has three types of loops: for loops that go through a list or range, while loops that run while a condition is true and until loops that run until a condition becomes true.

Q2. What is the difference between a while and until loop in shell scripting?

A. A while loop runs as long as the condition is true. An until loop runs as long as the condition is false. It stops when the condition becomes true.

Q3. How do I declare a variable in shell scripting?

A. You just write VARIABLE_NAME=value with no spaces around the = sign. To use it you put a $ in front like echo $VARIABLE_NAME.

Q4. Can I use shell scripting loops for DevOps automation?

A. Yes you can. Shell scripting loops are widely used in DevOps for automating deployments, monitoring disk and memory usage, processing configuration files and running health checks on servers.

Q5. Is shell scripting worth learning in 2026?

A. Yes it is. Shell scripting is still one of the in-demand skills for DevOps engineers, SREs and Linux system administrators. It is essential for working with cloud infrastructure, containers and CI/CD pipelines.

Get the curriculum

DevOps Course Online

100% secure · no spam · callback in 30 min

Recommended Course

Online DevOps course
BESTSELLER
AWSAzureGCPGen AI
Online DevOps Course
Job-Ready Program

Learn from Microsoft-certified experts with real projects, internship certification and dedicated placement support to help you land your next DevOps role.

6 Months
Duration
5–45 LPA
Opportunity range
300+ Hrs
Live sessions
IIT Patna
Certification
Next batch closing soon — limited seats
Live classes · 23 Nov
View full curriculum
© 2025 PAPERLIVE, All rights reserved

Disclaimer: PaperLive Learning offers skill-based training and professional upskilling courses only. Our programs are not postgraduate (PG) programs, diploma courses, or formal academic qualifications and do not award degrees or diplomas.

We strive to ensure that the information and pricing displayed on our website are accurate. However, course fees, content, duration, and promotional offers may change without prior notice. Applicable pricing at the time of enrollment will be communicated clearly.

Career outcomes depend on individual skills, effort, experience, performance, and market conditions. Placement statistics, salary figures, and success stories are for informational purposes only and do not guarantee similar results.

References to third-party platforms, certifications, and tools are for educational purposes only and do not imply endorsement or affiliation unless explicitly stated.