Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Shell Scripting
  • Kali Linux
  • Ubuntu
  • Red Hat
  • CentOS
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question
  • Python
  • R
  • Java
  • C
  • C++
  • JavaScript
  • DSA
Open In App
Next Article:
Break and Continue Keywords in Linux with Examples
Next article icon

Looping Statements | Shell Script

Last Updated : 03 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Looping Statements in Shell Scripting: There are total 3 looping statements that can be used in bash programming 

Table of Content

  • `while` statement in Shell Script in Linux
  • `for` statement in Shell Script in Linux
  • `until` statement in Shell Script in Linux
  • Examples of Looping Statements

To alter the flow of loop statements, two commands are used they are,  

  1. break
  2. continue

Their descriptions and syntax are as follows: 

`while` statement in Shell Script in Linux

Here the command is evaluated and based on the resulting loop will execute, if the command is raised to false then the loop will be terminated that. 

#/bin/bash
while <condition>
do
<command 1>
<command 2>
<etc>
done

Implementation of `While` Loop in Shell Script.

First, we create a file using a text editor in Linux. In this case, we are using `vim`editor.

vim looping.sh

You can replace "looping.sh" with the desired name.

Then we make our script executable using the `chmod` command in Linux.

chmod +x looping.sh

#/bin/bash

a=0

# lt is less than operator

#Iterate the loop until a less than 10

while [ $a -lt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done

Output:


While Loop in Linux
While Loop in Linux


Explanation:

  • #/bin/bash: Specifies that the script should be interpreted using the Bash shell.
  • a=0: Initializes a variable a with the value 0.
  • while [ $a -lt 10 ]: Initiates a while loop that continues as long as the value a is less than 10.
  • do: Marks the beginning of the loop's body.
  • echo $a: Prints the current value of a the console.
  • a=expr $a + 1``: Increments the value of a by 1. The expr command is used for arithmetic expressions.
  • done: Marks the end of the loop.

`for` statement in Shell Script in Linux

The for loop operates on lists of items. It repeats a set of commands for every item in a list. 
Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words). Each time the for loop executes, the value of the variable var is set to the next word in the list of words, word1 to wordN. 

Syntax:  

#/bin/bash
for <var> in <value1 value2 ... valuen>
do
<command 1>
<command 2>
<etc>
done

Implementation of `for` Loop with `break` statement in Shell Script.

First, we create a file using a text editor in Linux. In this case, we are using `vim`editor.

vim for.sh

You can replace "for.sh" with the desired name.

Then we make our script executable using the `chmod` command in Linux.

chmod +x for.sh

#/bin/bash

#Start of for loop

for a in 1 2 3 4 5 6 7 8 9 10
do

# if a is equal to 5 break the loop
if [ $a == 5 ]
then
break
fi

# Print the value
echo "Iteration no $a"
done

Output:


Break statement in for Loop in linux
Break statement in for Loop in linux


Explanation:

  • #/bin/bash: Specifies that the script should be interpreted using the Bash shell.
  • for a in 1 2 3 4 5 6 7 8 9 10: Initiates a for loop that iterates over the values 1 through 10, assigning each value to the variable a in each iteration.
  • do: Marks the beginning of the loop's body.
  • if [ $a == 5 ]: Checks if the current value a is equal to 5.
    • then: Marks the beginning of the conditional block to be executed if the condition is true.
      • break: Exits the loop if the condition is true.
    • fi: Marks the end of the conditional block.
  • echo "Iteration no $a": Prints a message indicating the current iteration number.
  • done: Marks the end of the loop.

The script sets up a for loop that iterates over the values 1 through 10. During each iteration, it checks if the value a is equal to 5. If it is, the loop is exited using the break statement. Otherwise, it prints a message indicating the current iteration number. The loop continues until it completes all iterations or until it encounters a break statement.

Implementation of `for` Loop with `continue` statement in Shell Script.

First, we create a file using a text editor in Linux. In this case, we are using `vim`editor.

vim for_continue.sh

You can replace "for_continue.sh" with the desired name.

Then we make our script executable using the `chmod` command in Linux.

chmod +x for_continue.sh

#/bin/bash

for a in 1 2 3 4 5 6 7 8 9 10
do

# if a = 5 then continue the loop and
# don't move to line 8

if [ $a == 5 ]
then
continue
fi
echo "Iteration no $a"
done

Output:


continue statement in for loop in Linux
continue statement in for loop in Linux


Explanation:

  • #/bin/bash: Specifies that the script should be interpreted using the Bash shell.
  • for a in 1 2 3 4 5 6 7 8 9 10: Initiates a for loop that iterates over the values 1 through 10, assigning each value to the variable a in each iteration.
  • do: Marks the beginning of the loop's body.
  • if [ $a == 5 ]: Checks if the current value a is equal to 5.
    • then: Marks the beginning of the conditional block to be executed if the condition is true.
      • continue: Skips the rest of the loop's body and goes to the next iteration if the condition is true.
    • fi: Marks the end of the conditional block.
  • echo "Iteration no $a": Prints a message indicating the current iteration number. This line is skipped if a is equal to 5 due to the continue statement.
  • done: Marks the end of the loop.

The script sets up a for loop that iterates over the values 1 through 10. During each iteration, it checks if the value a is equal to 5. If it is, the loop continues to the next iteration without executing the remaining statements in the loop's body. Otherwise, it prints a message indicating the current iteration number. The loop continues until it completes all iterations.

`until` statement in Shell Script in Linux

The until loop is executed as many times as the condition/command evaluates to false. The loop terminates when the condition/command becomes true. 

Syntax: 

#/bin/bash
until <condition>
do
<command 1>
<command 2>
<etc>
done


Implementing `until` Loop in Shell Scrip

First, we create a file using a text editor in Linux. In this case, we are using `vim`editor. 

vim until.sh

You can replace "until. sh" with the desired name.

Then we make our script executable using the `chmod` command in Linux.

chmod +x until.sh

#/bin/bash

a=0

# -gt is greater than operator
#Iterate the loop until a is greater than 10

until [ $a -gt 10 ]
do

# Print the values
echo $a

# increment the value
a=`expr $a + 1`
done

Output:


Unitl loop in Linux
Until loop in Linux


Explanation:

  • #/bin/bash: Specifies that the script should be interpreted using the Bash shell.
  • a=0: Initializes a variable a with the value 0.
  • until [ $a -gt 10 ]: Initiates a until loop that continues as long as the value a is not greater than 10.
  • do: Marks the beginning of the loop's body.
  • echo $a: Prints the current value of a the console.
  • a=expr $a + 1``: Increments the value of a by 1. The expr command is used for arithmetic expressions.
  • done: Marks the end of the loop.

Note: Shell scripting is a case-sensitive language, which means proper syntax has to be followed while writing the scripts.

Examples of Looping Statements

1. Iterating Over Colors Using a For Loop

First, we create a file using a text editor in Linux. In this case, we are using `vim`editor. 

vim color.sh

You can replace "color.sh" with the desired name.

Then we make our script executable using `chmod` command in Linux.

chmod +x color.sh

#/bin/bash

COLORS="red green blue"

# the for loop continues until it reads all the values from the COLORS

for COLOR in $COLORS
do
echo "COLOR: $COLOR"
done

Output:


For until in Linux
For until in Linux


Explanation:

  • Initialization of Colors:
    • COLORS="red green blue": Initializes a variable named COLORS with a space-separated list of color values ("red", "green", and "blue").
  • For Loop Iteration:
    • for COLOR in $COLORS: Initiates a for loop that iterates over each value in the COLORS variable.
      • Loop Body:
        • echo "COLOR: $COLOR": Prints a message for each color, displaying the current color value.
    • The loop continues until it processes all the values present in the COLORS variable.

This example demonstrates a simple for loop in Bash, iterating over a list of colors stored in the COLORS variable. The loop prints a message for each color, indicating the current color being processed. The loop iterates until all color values are exhausted.

2. Creating an Infinite Loop with "while true" in Shell Script

First we create a file using a text editor in Linux. In this case we are using `vim`editor. 

vim infinite.sh

You can replace "infinite.sh" with desired name.

Then we make our script executable using `chmod` command in Linux.

chmod +x infinite.sh

#/bin/bash

while true
do

# Command to be executed
# sleep 1 indicates it sleeps for 1 sec
echo "Hi, I am infinity loop"
sleep 1
done

Output:


infinite loop in linux
infinite loop in linux


Explanation:

Infinite Loop Structure:

  • while true: Initiates a while loop that continues indefinitely as the condition true is always true.
    • Loop Body:
      • echo "Hi, I am infinity loop": Prints a message indicating that the script is in an infinite loop.
      • sleep 1: Pauses the execution of the loop for 1 second before the next iteration.
  • The loop continues indefinitely, executing the commands within its body repeatedly.

This example showcases the creation of an infinite loop using the while true construct in Bash. The loop continuously prints a message indicating its status as an infinite loop and includes a sleep 1 command, causing a one-second delay between iterations. Infinite loops are often used for processes that need to run continuously until manually interrupted.

3. Interactive Name Confirmation Loop

First we create a file using a text editor in Linux. In this case we are using `vim`editor. 

vim name.sh

You can replace "name.sh" with desired name.

Then we make our script executable using `chmod` command in Linux.

chmod +x name.sh

#/bin/bash

CORRECT=n
while [ "$CORRECT" == "n" ]
do

# loop discontinues when you enter y i.e., when your name is correct
# -p stands for prompt asking for the input

read -p "Enter your name:" NAME
read -p "Is ${NAME} correct? " CORRECT
done

Output:


Interactive script in Linux
Interactive script in Linux


Explanation:

  • Initialization:
    • CORRECT=n: Initializes a variable named CORRECT with the value "n". This variable is used to control the loop.
  • Interactive Loop:
    • while [ "$CORRECT" == "n" ]: Initiates a while loop that continues as long as the value of CORRECT is equal to "n".
      • Loop Body:
        • read -p "Enter your name:" NAME: Prompts the user to enter their name and stores the input in the NAME variable.
        • read -p "Is ${NAME} correct? " CORRECT: Asks the user to confirm if the entered name is correct and updates the CORRECT variable accordingly.
    • The loop continues until the user enters "y" (indicating the correct name).

This example demonstrates an interactive loop that prompts the user to enter their name and then asks for confirmation. The loop continues until the user confirms that the entered name is correct by inputting "y". The loop utilizes the `read` command for user input and updates the `CORRECT` variable to control the loop flow.

Conclusion

In this article we discussed looping statements in Bash scripting, covering while, for, and until loops. It introduces the use of break and continue statements to modify loop behavior. Practical examples illustrate the implementation of loops, including iterating over color values, creating infinite loops, and building an interactive loop for user input validation. The guide offers a concise yet informative resource for understanding and utilizing looping constructs in Bash scripting.


Next Article
Break and Continue Keywords in Linux with Examples
author
bilal-hungund
Improve
Article Tags :
  • Misc
  • Linux-Unix
  • Shell
  • Shell Script
Practice Tags :
  • Misc

Similar Reads

  • Introduction to Linux Shell and Shell Scripting
    If we are using any major operating system, we are indirectly interacting with the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting with the shell by using the terminal. In this article we will discuss Linux shells and shell scripting so before understandi
    7 min read
  • Introduction to Shell Scripting

    • How to Create a Shell Script in linux
      Shell is an interface of the operating system. It accepts commands from users and interprets them to the operating system. If you want to run a bunch of commands together, you can do so by creating a shell script. Shell scripts are very useful if you need to do a task routinely, like taking a backup
      7 min read

    • Different Shells in Linux
      SHELL is a program which provides the interface between the user and an operating system. When the user logs in OS starts a shell for user. Kernel controls all essential computer operations, and provides the restriction to hardware access, coordinates all executing utilities, and manages Resources b
      5 min read

    Basic Shell Commands in Linux

    • Basic Shell Commands in Linux: Complete List
      Anyone using Linux should become an expert in the essential shell commands, as they form the backbone of working with the Linux terminal. These commands enable you to navigate the system, manage files, handle processes, and configure settings effectively. The Linux shell serves as an interface for u
      5 min read

    • Linux Directory Structure
      Prerequisite: Linux File Hierarchy Structure In Linux/Unix operating system everything is a file even directories are files, files are files, and devices like mouse, keyboard, printer, etc are also files. Here we are going to see the Directory Structure in Linux. Types of files in the Linux system.
      5 min read

    • Input Output Redirection in Linux
      In Linux, whenever an individual runs a command, it can take input, give output, or do both. Redirection helps us redirect these input and output functionalities to the files or folders we want, and we can use special commands or characters to do so. For example, if we run the "date" command, it giv
      4 min read

    Variables and Data Types

    • Shell Scripting - Shell Variables
      A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which
      6 min read

    • Shell Scripting - Rules for Naming Variable Name
      Variables are quite important in any script or program, so we need to understand what is the convention to name these variables. There are certain rules and standards to keep in mind while giving names to the variables in Shell scripting. In this article, we will discuss and list down all the rules
      4 min read

    • String Manipulation in Shell Scripting
      String Manipulation is defined as performing several operations on a string resulting change in its contents. In Shell Scripting, this can be done in two ways: pure bash string manipulation, and string manipulation via external commands. Basics of pure bash string manipulation: 1. Assigning content
      4 min read

    • Array Basics in Shell Scripting | Set 1
      Consider a situation if we want to store 1000 numbers and perform operations on them. If we use a simple variable concept then we have to create 1000 variables and perform operations on them. But it is difficult to handle a large number of variables. So, it is good to store the same type of values i
      6 min read

    Control Structures

    • Conditional Statements | Shell Script
      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 Their description with syntax is as follows: if statement
      3 min read

    • Looping Statements | Shell Script
      Looping Statements in Shell Scripting: There are total 3 looping statements that can be used in bash programming  Table of Content `while` statement in Shell Script in Linux`for` statement in Shell Script in Linux`until` statement in Shell Script in LinuxExamples of Looping StatementsTo alter the fl
      10 min read

    • Break and Continue Keywords in Linux with Examples
      Both “break” and “continue” are used to transfer control of the program to another part of the program. It is used within loops to alter the flow of the loop and terminate the loop or skip the current iteration. break The break statement is used to terminate the loop and can be used within a while,
      3 min read

    Functions and Script Organization

    • Shell Scripting - Functions and it's types
      Shell scripting is a powerful tool used to automate tasks in Unix-like operating systems. A shell serves as a command-line interpreter, and shell scripts often perform file manipulation, program execution, and text output. Here, we'll look into functions in shell scripting, exploring their structure
      5 min read

    • How To Pass and Parse Linux Bash Script Arguments and Parameters
      Parsing and Passing of Arguments into bash scripts/ shell scripts is quite similar to the way in which we pass arguments to the functions inside Bash scripts. We'll see the actual process of passing on the arguments to a script and also look at the way to access those arguments inside the script. Pa
      7 min read

    Input And Output

    • Shell Scripting - Standard Input, Output and Error
      Working on Linux applications we have several ways to get information from outside and to put it inside: command line args, environment variables, files. All of these sources are legal and good. But it has a finite size. Another way to establish communication is standard streams: input stream (stdin
      7 min read

    • Shell Script to Perform Operations on a File
      Most of the time, we use shell scripting to interact with the files. Shell scripting offers some operators as well as some commands to check and perform different properties and functionalities associated with the file. For our convenience, we create a file named 'geeks.txt' and another .sh file (or
      5 min read

    Command-Line Arguments and Options

    • Shell Script to Demonstrate Special Parameters With Example
      Here, we are going to see what are the special Parameters of the shell script. Before that first, let's understand what is parameters in the shell. The parameter is the entity that stores the value. The variables are the parameters that are defined by the user to use in that specific shell script. A
      5 min read

    Error Handling and Debugging

    • User Space Debugging Tools in Linux
      In this article, we will discuss debugging tools in Linux. Debugging Tools are those programs that allow us to monitor, control, and correct other program's error while they execute. Some of the debugging tools are as follows:- 'print Statement'Querying (/proc, /sys etc)Tracing (strace/ltrace)Valgri
      3 min read

    • Shell Scripting - System Logging
      Shell scripting is a way of automating tasks and operations on a computer system by writing scripts and programs in a shell or terminal environment. These scripts can run commands, access system resources, and process data. Shell scripts are often used to automate repetitive tasks, such as backups,
      9 min read

    Regular Expressions

    • How to Use Regular Expressions (RegEx) on Linux
      Regexps are acronyms for regular expressions. Regular expressions are special characters or sets of characters that help us to search for data and match the complex pattern. Regexps are most commonly used with the Linux commands:- grep, sed, tr, vi. The following are some basic regular expressions:
      5 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences