A Bash for loop is used to repeat a command or a group of commands multiple times. If you are learning Bash scripting, loops are very important because they help you automate repetitive tasks. Instead of writing the same command again and again, you can use a for loop to run it automatically.
Bash for loops are commonly used for file handling, user management, log analysis, backups, cybersecurity automation, and system administration. For example, you can loop through files in a directory, scan multiple IP addresses, rename files, or check several services at once.
A for loop runs commands for each item in a list.
Basic syntax:
for item in listdo commanddone
You can also write it in one line:
for item in list; do command; done
The loop starts with for and ends with done.
Create a new Bash script:
nano for-loop.sh
Add the following code:
#!/bin/bashfor name in Kali Ubuntu Debian Fedorado echo "Linux distribution: $name"done
Save the file and run it:
chmod +x for-loop.sh./for-loop.sh
Output:
Linux distribution: KaliLinux distribution: UbuntuLinux distribution: DebianLinux distribution: Fedora
In this example, the variable name stores each item one by one.
You can use a for loop with numbers using brace expansion.
#!/bin/bashfor number in {1..5}do echo "Number: $number"done Output:
Number: 1Number: 2Number: 3Number: 4Number: 5
This is useful when you want to repeat a command a fixed number of times.
A common use of for loops is to process files in a directory.
#!/bin/bashfor file in *.txtdo echo "Found text file: $file"done
This script checks all .txt files in the current directory and prints their names.
You can also rename multiple files using a loop.
#!/bin/bashfor file in *.logdo mv "$file" "backup-$file"done
This script adds backup- before every .log file name.
For cybersecurity learners, loops are useful for scanning multiple hosts.
#!/bin/bashfor ip in 192.168.1.{1..5}do ping -c 1 $ipdone This script pings IP addresses from 192.168.1.1 to 192.168.1.5.
The Bash for loop is a powerful feature for automation. It helps you repeat commands, process files, handle numbers, and automate Linux tasks easily.
For beginners, learning for loops is an important step in Bash scripting. Once you understand this concept, you can create better scripts for file management, backups, system monitoring, cybersecurity checks, and Linux automation.
Introduction A self-signed SSL certificate is a certificate that is created and signed by the…
Introduction Debugging is an important part of Bash scripting. When a script does not work…
Introduction Cron jobs are used in Linux to run commands or Bash scripts automatically at…
Introduction Pipes are an important feature in Linux and Bash scripting. A pipe allows you…
Introduction The grep, awk, and sed commands are powerful text-processing tools in Linux. They are…
Introduction Working with files and directories is one of the most important skills in Bash…