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.
Journalists use OSINT to verify public information before publishing. In 2026, misinformation, AI-generated images, fake…
DockerĀ is an open-source platform that lets you package and run applications inside containers. Each container…
PostgreSQL (often called Postgres) is an open-source relational database system. It supports advanced features like JSON…
Xrdp is an open-source server that lets you connect to your Ubuntu machine from another computer…
Apache Tomcat is an open-source web server and Java servlet container. It is one of the…
Keeping your Ubuntu system updated is one of the best ways to protect it. Security…