Bash Scripting Loops

LinuxLinuxBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to use loops in Bash scripting. Loops allow you to repeat a set of instructions multiple times, making your scripts more efficient and flexible. We will cover three types of loops: for, while, and until. Additionally, we will explore the break and continue statements, which allow you to control the loop execution.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/VariableHandlingGroup(["`Variable Handling`"]) shell(("`Shell`")) -.-> shell/AdvancedScriptingConceptsGroup(["`Advanced Scripting Concepts`"]) shell(("`Shell`")) -.-> shell/SystemInteractionandConfigurationGroup(["`System Interaction and Configuration`"]) shell/ControlFlowGroup -.-> shell/if_else("`If-Else Statements`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/BasicFileOperationsGroup -.-> linux/ls("`Content Listing`") linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") linux/BasicFileOperationsGroup -.-> linux/chmod("`Permission Modifying`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/BasicSyntaxandStructureGroup -.-> shell/quoting("`Quoting Mechanisms`") shell/VariableHandlingGroup -.-> shell/variables_decl("`Variable Declaration`") shell/VariableHandlingGroup -.-> shell/variables_usage("`Variable Usage`") shell/VariableHandlingGroup -.-> shell/str_manipulation("`String Manipulation`") shell/VariableHandlingGroup -.-> shell/arrays("`Arrays`") shell/VariableHandlingGroup -.-> shell/param_expansion("`Parameter Expansion`") shell/ControlFlowGroup -.-> shell/for_loops("`For Loops`") shell/ControlFlowGroup -.-> shell/while_loops("`While Loops`") shell/ControlFlowGroup -.-> shell/until_loops("`Until Loops`") shell/ControlFlowGroup -.-> shell/cond_expr("`Conditional Expressions`") shell/AdvancedScriptingConceptsGroup -.-> shell/arith_expansion("`Arithmetic Expansion`") shell/AdvancedScriptingConceptsGroup -.-> shell/cmd_substitution("`Command Substitution`") shell/AdvancedScriptingConceptsGroup -.-> shell/subshells("`Subshells and Command Groups`") shell/SystemInteractionandConfigurationGroup -.-> shell/globbing_expansion("`Globbing and Pathname Expansion`") linux/FileandDirectoryManagementGroup -.-> linux/wildcard("`Wildcard Character`") subgraph Lab Skills shell/if_else -.-> lab-153900{{"`Bash Scripting Loops`"}} linux/echo -.-> lab-153900{{"`Bash Scripting Loops`"}} linux/cd -.-> lab-153900{{"`Bash Scripting Loops`"}} linux/ls -.-> lab-153900{{"`Bash Scripting Loops`"}} linux/touch -.-> lab-153900{{"`Bash Scripting Loops`"}} linux/chmod -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/comments -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/quoting -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/variables_decl -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/variables_usage -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/str_manipulation -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/arrays -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/param_expansion -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/for_loops -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/while_loops -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/until_loops -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/cond_expr -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/arith_expansion -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/cmd_substitution -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/subshells -.-> lab-153900{{"`Bash Scripting Loops`"}} shell/globbing_expansion -.-> lab-153900{{"`Bash Scripting Loops`"}} linux/wildcard -.-> lab-153900{{"`Bash Scripting Loops`"}} end

The for Loop

The for loop is used to iterate over a list of values or the output of a command. Here is the basic syntax:

for item in [list]
do
    command(s)...
done

Create a file called ~/project/for.sh.

To loop through an array, you can use the following example:

NAMES=("Joe" "Jenny" "Sara" "Tony")
for name in "${NAMES[@]}"; do
  echo "My name is $name"
done
cd ~/project
chmod +x for.sh
./for.sh
My name is Joe
My name is Jenny
My name is Sara
My name is Tony

To loop through the output of a command, you can use the following example:

## create some txt files
touch file1.txt file2.txt file3.txt

## loop through the output of ls
for file in $(ls *.txt); do
  echo "File is: $file"
done
File is: file1.txt
File is: file2.txt
File is: file3.txt

The while Loop

The while loop is used to execute a block of code as long as a certain condition is true. Here is the basic syntax:

while [ condition ]
do
    command(s)...
done

Here is an example that counts down from 4:

count=4
while [ $count -gt 0 ]; do
  echo "Value of count is: $count"
  count=$(($count - 1))
done

Create a file called ~/project/while.sh.

cd ~/project
chmod +x while.sh
./while.sh
Value of count is: 4
Value of count is: 3
Value of count is: 2
Value of count is: 1

The until Loop

The until loop is the opposite of the while loop. It continues executing a block of code until a certain condition becomes true. Here is the basic syntax:

until [ condition ]
do
    command(s)...
done

Here is an example that counts up to 5:

count=1
until [ $count -gt 5 ]; do
  echo "Value of count is: $count"
  count=$(($count + 1))
done

Revise the file ~/project/while.sh to use the until loop.

Value of count is: 1
Value of count is: 2
Value of count is: 3
Value of count is: 4
Value of count is: 5

The break and continue Statements

The break and continue statements can be used to control the execution of a loop. break is used to exit the loop completely, while continue skips the rest of the current iteration and moves to the next one.

Here is an example that prints numbers from 0 to 4:

count=0
while [ $count -ge 0 ]; do
  echo "Value of count is: $count"
  count=$((count + 1))
  if [ $count -ge 5 ]; then
    break
  fi
done

Here is an example that prints only odd numbers from 1 to 10:

count=0
while [ $count -lt 10 ]; do
  count=$((count + 1))
  if [ $(($count % 2)) = 0 ]; then
    continue
  fi
  echo $count
done

Revise the file ~/project/while.sh to use the break and continue statements.

Value of count is: 1
Value of count is: 3
Value of count is: 5
Value of count is: 7
Value of count is: 9

Summary

In this lab, you learned how to use loops in Bash scripting. The for, while, and until loops allow you to repeat a block of code multiple times. You also learned about the break and continue statements, which help you control the loop execution. With this knowledge, you can write more efficient and flexible Bash scripts.

Other Linux Tutorials you may like