0
0
Bash Scriptingscripting~5 mins

Why loops repeat tasks efficiently in Bash Scripting

Choose your learning style9 modes available
Introduction

Loops help you do the same job many times without writing the same code again and again. This saves time and makes your script shorter and easier to read.

When you want to print numbers from 1 to 10.
When you need to check many files one by one.
When you want to repeat a command for each item in a list.
When you want to automate repetitive tasks like backups.
When you want to process multiple user inputs automatically.
Syntax
Bash Scripting
for variable in list
 do
   commands
 done

The for loop goes through each item in the list one by one.

Inside the loop, you write commands that use the current item stored in variable.

Examples
This loop prints 'Number 1', 'Number 2', and 'Number 3'.
Bash Scripting
for i in 1 2 3
 do
   echo "Number $i"
 done
This loop lists all files ending with .txt in the current folder.
Bash Scripting
for file in *.txt
 do
   echo "File: $file"
 done
Sample Program

This script counts from 1 to 5, printing each number with the word 'Counting:'.

Bash Scripting
#!/bin/bash

for i in 1 2 3 4 5
 do
   echo "Counting: $i"
 done
OutputSuccess
Important Notes

Make sure to use done to end the loop.

You can loop over words, numbers, or file names.

Loops help avoid mistakes by not repeating code manually.

Summary

Loops repeat tasks to save time and effort.

They make scripts shorter and easier to understand.

Use loops when you have many similar jobs to do.