âšď¸ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.3 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://runcloud.io/blog/bash-for-loop |
| Last Crawled | 2026-03-31 01:45:23 (8 days ago) |
| First Indexed | 2024-01-31 15:04:54 (2 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Introduction to Bash For Loops: A Beginnerâs Guide |
| Meta Description | In this article, weâll demystify the 'for' loop in Bash scripting. Whether youâre a developer, sysadmin, or just curious about the command line, understanding |
| Meta Canonical | null |
| Boilerpipe Text | If youâre new to the command line and Linux, fear not! You donât need to be a Linux expert to start using the power of the terminal.
Table of Contents
Why Are âForâ Loops Necessary?
Basic Syntax of Bash âForâ Loop
Using Bash âForâ Loop
Looping through Files and Directories
Iterating over a Range of Numbers
Using âforâ with Command Substitution
Nested âforâ Loops
Final Thoughts
In this article, weâll demystify the âforâ loop in Bash scripting. Whether youâre a developer, sysadmin, or just curious about the command line, understanding âforâ loops is essential.
Why Are âForâ Loops Necessary?
The â
forâ loop
is a fundamental construct that allows you to repeat a set of commands or actions multiple times. Itâs like having a trusty assistant who diligently performs a task for you over and over again. Whether youâre processing files, managing directories, or automating tasks, there are many scenarios when loops are useful:
File Processing and Batch Operations
:
Loop through files in a directory to perform batch operations, such as renaming, moving, or compressing them.
Process log files, extract relevant information, and generate reports.
System Administration and Configuration
:
Iterate over a list of user accounts to apply changes (e.g., setting permissions, updating passwords).
Configure network interfaces, firewall rules, or services on multiple servers.
Backup and Archiving
:
Create backup scripts that loop through directories and files to archive or synchronize data.
Rotate log files by compressing older logs and keeping a specified number of recent ones.
Automating Repetitive Tasks
:
Run commands on multiple remote servers via SSH.
Schedule regular tasks (e.g., backups, database maintenance) using cron jobs.
Data Processing and Transformation
:
Parse CSV files or other structured data formats.
Transform data (e.g., converting file formats, extracting specific fields).
Loops in general are versatile and can be adapted to various scenarios. They allow you to iterate over lists, directories, or any other collection of items in your scripts.
In this post, weâll explore the basic syntax of âforâ loops, and demonstrate their versatility with practical examples. By the end, youâll be ready to wield this powerful tool in your Linux journey.
Basic Syntax of Bash âForâ Loop
A
'for'
loop is a control structure in programming that allows you to repeat a set of commands for each item in a list. Itâs like a conveyor belt that processes each item one by one.
Syntax
:
for variable in list
: This line initializes a loop. The
variable
represents the current item from the
list
.
do
: This marks the beginning of the loop body.
# Commands to execute for each item in the list
: Here, you can put any commands or actions you want to perform on each item.
done
: This marks the end of the loop.
for
variable
in
list
do
# Commands to execute for each item in the list
done
Explanation
:
You define a
variable
(usually a single letter) to keep track of the current item.
The
list
contains multiple items (e.g., filenames, numbers, or strings).
For each item in the
list
, the commands inside the loop are executed.
Once all items are processed, the loop ends.
Execution Frequency
:
The
for
loop executes once for each item in the specified
list
.
If there are
n
items in the list, the loop will run
n
times.
For example, if you have a list of three filenames (
file1.txt
,
file2.txt
, and
file3.txt
), the loop will execute three times, once for each filename.
for
filename
in
file1
.
txt
file2
.
txt
file3
.
txt
do
if
[
"$filename"
=
=
"file2.txt"
]
;
then
echo
"Found file2.txt! Exiting loop."
break
fi
echo
"Processing $filename"
done
Using Bash âForâ Loop
Looping through Files and Directories
You can use a
'for'
loop to process files or directories. This is ideal if you want to traverse through a directory which has a large number of files, or if the number of files keep changing.
#!/bin/bash
for
file
in
/
path
/
to
/
files
/*; do
echo "Processing file: $file"
# Add your custom commands here
done
Iterating over a Range of Numbers
To loop through a range of numbers, use the
{start..end}
notation. If you want to run the loop a fixed number of times, you can create a list of numbers using this format.
#!/bin/bash
for
i
in
{
1
.
.
5
}
;
do
echo
"Number: $i"
done
Using âforâ with Command Substitution
The âforâ loop is flexible and powerful. You can redirect the output of other commands in the loop, and then process each item in the list.
#!/bin/bash
for
user
in
$
(
cut
-
d
:
-
f1
/
etc
/
passwd
)
;
do
echo
"User: $user"
done
Nested âforâ Loops
If a simple âforâ loop isnât enough, you can use multiple âforâ loops together to achieve more complex functionality.
#!/bin/bash
for
outer
in
A
B
C
;
do
for
inner
in
1
2
3
;
do
echo
"$outer->$inner"
done
done
Final Thoughts
Youâve now unlocked the potential of
Bash for loops
. It is like a Swiss Army knife for your command line adventures. Mastering the âforâ loop opens up endless possibilities for automating tasks and managing data efficiently in your Linux environment.
Remember, the command line need not be intimidating, but if you do find it a bit daunting then you should check out
RunCloud
, a web platform to manage your servers that
works with any cloud provider
.
Sign up for RunCloud
and experience the best of both worlds:
Web-Friendly Dashboard
: Get started quickly without diving into complex Linux commands. RunCloud provides an intuitive interface for managing your servers.
Command Line Freedom
: If youâre a terminal enthusiast, RunCloud gives you the flexibility to tinker with the command line whenever you wish. |
| Markdown | [Blog](https://runcloud.io/blog)
Search...
`Ctrl` `+`
#### Start typing to begin search
Enter a search term to find results
in the blog.
- [Products]()
#### Modern server management panel
The enterprise-grade platform for server management.
[Server Management](https://runcloud.io/server-management)
[Backup](https://runcloud.io/backup)
[Atomic Deployment](https://runcloud.io/atomic-deployment)
[Team](https://runcloud.io/team)
[Arch](https://runcloud.io/arch)
[RunCache](https://runcloud.io/runcache)
[Migration](https://runcloud.io/migration)
- [Resources]()
#### Resources
Get help and learn more about our products offering.
[Blog](https://runcloud.io/blog)
[Documentation](https://runcloud.io/docs)
[API & Developers](https://runcloud.io/docs/api)
[Changelog](https://runcloud.io/changelog)
[Community](https://community.runcloud.io/)
[Status Page](https://status.runcloud.io/)
- [Pricing](https://runcloud.io/pricing)
- [Company]()
#### Company
Get help and learn more about our products offering.
[About Us](https://runcloud.io/company)
[Ambassadors](https://runcloud.io/company/ambassador)
[Career](https://runcloud.io/careers)
[Legal](https://runcloud.io/legal/tos)
[Newsroom](https://runcloud.io/company/newsroom)
[Bug Bounty Programme](https://runcloud.io/bug-bounty-programme)
[Trust & Security](https://runcloud.io/security)
[Education](https://runcloud.io/education)
[Contact Us](mailto:hello@runcloud.io?subject=[Hello])
- [Login](https://manage.runcloud.io/auth/login?utm_source=runcloudwebsite&utm_medium=blog&utm_campaign=blog-header)
- [Get Started](https://manage.runcloud.io/auth/onboard?utm_source=runcloudwebsite&utm_medium=blog&utm_campaign=blog-header)
- [All Posts](https://runcloud.io/blog)
- [News](https://runcloud.io/blog/category/new)
- [Server Management](https://runcloud.io/blog/category/server-management)
- [WordPress](https://runcloud.io/blog/category/wordpress)
- [Security](https://runcloud.io/blog/category/security)
- [Laravel](https://runcloud.io/blog/category/laravel)
- [Cloud Education](https://runcloud.io/blog/category/tutorial)
- [Cloud Education](https://runcloud.io/blog/category/tutorial)
- â˘
- [Linux](https://runcloud.io/blog/category/linux)
# Introduction to Bash For Loops: A Beginnerâs Guide

RunCloud Team
- Last Updated Oct 17, 2024
- â˘
- Reading Time 3 min read
If youâre new to the command line and Linux, fear not! You donât need to be a Linux expert to start using the power of the terminal.
Table of Contents
- [Why Are âForâ Loops Necessary?](https://runcloud.io/blog/bash-for-loop#why-are-for-loops-necessary)
- [Basic Syntax of Bash âForâ Loop](https://runcloud.io/blog/bash-for-loop#basic-syntax-of-bash-for-loop)
- [Using Bash âForâ Loop](https://runcloud.io/blog/bash-for-loop#using-bash-for-loop)
- [Looping through Files and Directories](https://runcloud.io/blog/bash-for-loop#looping-through-files-and-directories)
- [Iterating over a Range of Numbers](https://runcloud.io/blog/bash-for-loop#iterating-over-a-range-of-numbers)
- [Using âforâ with Command Substitution](https://runcloud.io/blog/bash-for-loop#using-for-with-command-substitution)
- [Nested âforâ Loops](https://runcloud.io/blog/bash-for-loop#nested-for-loops)
- [Final Thoughts](https://runcloud.io/blog/bash-for-loop#final-thoughts)
In this article, weâll demystify the âforâ loop in Bash scripting. Whether youâre a developer, sysadmin, or just curious about the command line, understanding âforâ loops is essential.
## **Why Are âForâ Loops Necessary?**
The â**forâ loop** is a fundamental construct that allows you to repeat a set of commands or actions multiple times. Itâs like having a trusty assistant who diligently performs a task for you over and over again. Whether youâre processing files, managing directories, or automating tasks, there are many scenarios when loops are useful:
1. **File Processing and Batch Operations**:
- Loop through files in a directory to perform batch operations, such as renaming, moving, or compressing them.
- Process log files, extract relevant information, and generate reports.
2. **System Administration and Configuration**:
- Iterate over a list of user accounts to apply changes (e.g., setting permissions, updating passwords).
- Configure network interfaces, firewall rules, or services on multiple servers.
3. **Backup and Archiving**:
- Create backup scripts that loop through directories and files to archive or synchronize data.
- Rotate log files by compressing older logs and keeping a specified number of recent ones.
4. **Automating Repetitive Tasks**:
- Run commands on multiple remote servers via SSH.
- Schedule regular tasks (e.g., backups, database maintenance) using cron jobs.
5. **Data Processing and Transformation**:
- Parse CSV files or other structured data formats.
- Transform data (e.g., converting file formats, extracting specific fields).
Loops in general are versatile and can be adapted to various scenarios. They allow you to iterate over lists, directories, or any other collection of items in your scripts.
In this post, weâll explore the basic syntax of âforâ loops, and demonstrate their versatility with practical examples. By the end, youâll be ready to wield this powerful tool in your Linux journey.
***
## Basic Syntax of Bash âForâ Loop
A `'for'` loop is a control structure in programming that allows you to repeat a set of commands for each item in a list. Itâs like a conveyor belt that processes each item one by one.
**Syntax**:
- `for variable in list`: This line initializes a loop. The `variable` represents the current item from the `list`.
- `do`: This marks the beginning of the loop body.
- `# Commands to execute for each item in the list`: Here, you can put any commands or actions you want to perform on each item.
- `done`: This marks the end of the loop.
```
Copy
```
**Explanation**:
- You define a `variable` (usually a single letter) to keep track of the current item.
- The `list` contains multiple items (e.g., filenames, numbers, or strings).
- For each item in the `list`, the commands inside the loop are executed.
- Once all items are processed, the loop ends.
**Execution Frequency**:
- The `for` loop executes once for each item in the specified `list`.
- If there are **n** items in the list, the loop will run **n** times.
- For example, if you have a list of three filenames (`file1.txt`, `file2.txt`, and `file3.txt`), the loop will execute three times, once for each filename.
```
Copy
```

## Using Bash âForâ Loop
### Looping through Files and Directories
You can use a `'for'` loop to process files or directories. This is ideal if you want to traverse through a directory which has a large number of files, or if the number of files keep changing.
```
Copy
```

### Iterating over a Range of Numbers
To loop through a range of numbers, use the `{start..end}` notation. If you want to run the loop a fixed number of times, you can create a list of numbers using this format.
```
Copy
```

### Using âforâ with Command Substitution
The âforâ loop is flexible and powerful. You can redirect the output of other commands in the loop, and then process each item in the list.
```
Copy
```

### Nested âforâ Loops
If a simple âforâ loop isnât enough, you can use multiple âforâ loops together to achieve more complex functionality.
```
Copy
```

## **Final Thoughts**
Youâve now unlocked the potential of **Bash for loops**. It is like a Swiss Army knife for your command line adventures. Mastering the âforâ loop opens up endless possibilities for automating tasks and managing data efficiently in your Linux environment.
Remember, the command line need not be intimidating, but if you do find it a bit daunting then you should check out **[RunCloud](https://runcloud.io/)**, a web platform to manage your servers that **works with any cloud provider**. [Sign up for RunCloud](https://manage.runcloud.io/auth/onboard) and experience the best of both worlds:
- **Web-Friendly Dashboard**: Get started quickly without diving into complex Linux commands. RunCloud provides an intuitive interface for managing your servers.
- **Command Line Freedom**: If youâre a terminal enthusiast, RunCloud gives you the flexibility to tinker with the command line whenever you wish.
## About the author(s)

RunCloud TeamAuthor
### Deploy & manage production-grade cloud infrastructure.
Trusted by brands from startup to enterprise. With everything from backups, staging, cloning, atomic deployments, and more â RunCloud makes it easy to manage your own production-grade infrastructure.
[Get Started Now](https://manage.runcloud.io/auth/onboard?utm_source=runcloudwebsite&utm_medium=blog&utm_campaign=blog-sidebar)
Posts you may like
[Cloud Education  RunCloud Team May 05, 2020 5 min read How To Use Redis Object Cache To Speed Up Dynamic WordPress SiteWith RunCloud, you donât need to be a Linux expert to host high-performance WordPress websites, both âstaticâ WordPress sites (simple blog) and âdynamicâ WordPress sites (WooCommerce and membership). For any types of highly dynamic websites, you can use Redis Object Cache to use less database resources by caching the results of complex database queries, speed âŚ](https://runcloud.io/blog/redis-object-cache)
[Cloud Education  RunCloud Team Dec 02, 2025 6 min read How to Install Docker on Windows Server 2016, 2019 & 2022Although Linux remains the easier and more efficient platform for most containers, Windows Server still plays a major role in many production environments. If your applications, tooling, or infrastructure tie you to Windows, mastering Docker on Windows Server becomes a practical requirement. You might be working with Windows containers because: In this guide, weâll explain âŚ](https://runcloud.io/blog/installing-docker-on-windows-server)
[Cloud Education  RunCloud Team May 21, 2020 6 min read How To Install ImageMagick PHP Extension (Imagick)Do you want to manipulate images in various ways without using complex tools or libraries? If you answered yes, then you need to know about ImageMagick, a powerful and versatile image processing software that works seamlessly with PHP web applications. Even if you are using a CMS or a framework such as WordPress or Laravel âŚ](https://runcloud.io/blog/how-to-install-imagemagick)
[Cloud Education  RunCloud Team Jun 21, 2023 7 min read How to Test WordPress 6 â and Every Subsequent ReleaseIs your website losing potential customers? Shocking statistics reveal that 64% of visitors abandon slow and glitchy sites! Itâs vital that you test your websites thoroughly to provide your users with a first-rate browsing experience if you want to stand any chance of increasing your sales. In this article, we will detail the steps you âŚ](https://runcloud.io/blog/how-to-test-wordpress)
[Linux  RunCloud Team Feb 15, 2025 7 min read How to Restrict WordPress Admin Access by IP Address (Easy Guide)Open access to your wp-admin directory and wp-login.php makes it a prime target for brute-force attacks and unauthorized access. By whitelisting specific IP addresses and implementing WordPress admin access control, you can effectively stop hackers, block automated bots, and significantly reduce failed login attempts. This WordPress tutorial will show you how to restrict WordPress admin âŚ](https://runcloud.io/blog/restrict-wordpress-admin-access-ip-address)
[Cloud Education  RunCloud Team Sep 17, 2025 5 min read How to Fix the Cloudflare HTTP Error 526If youâre seeing Cloudflare HTTP Error 526 (Invalid SSL Certificate) on your site, it means Cloudflare couldnât verify the SSL certificate on your server. The result is that your visitors are blocked from accessing your website until itâs fixed. In this guide, weâll show you how to fix the Cloudflare HTTP Error 526 step by âŚ](https://runcloud.io/blog/fix-cloudflare-http-error-526)
## Comments
### Add to discussion
Your email address will not be published
Š 2026 RunCloud Sdn Bhd
- [Terms of Service](https://runcloud.io/legal/tos)
- [Privacy Policy](https://runcloud.io/legal/privacy-policy)
- [Cookie Policy](https://runcloud.io/legal/cookie-policy) |
| Readable Markdown | If youâre new to the command line and Linux, fear not! You donât need to be a Linux expert to start using the power of the terminal.
Table of Contents
- [Why Are âForâ Loops Necessary?](https://runcloud.io/blog/bash-for-loop#why-are-for-loops-necessary)
- [Basic Syntax of Bash âForâ Loop](https://runcloud.io/blog/bash-for-loop#basic-syntax-of-bash-for-loop)
- [Using Bash âForâ Loop](https://runcloud.io/blog/bash-for-loop#using-bash-for-loop)
- [Looping through Files and Directories](https://runcloud.io/blog/bash-for-loop#looping-through-files-and-directories)
- [Iterating over a Range of Numbers](https://runcloud.io/blog/bash-for-loop#iterating-over-a-range-of-numbers)
- [Using âforâ with Command Substitution](https://runcloud.io/blog/bash-for-loop#using-for-with-command-substitution)
- [Nested âforâ Loops](https://runcloud.io/blog/bash-for-loop#nested-for-loops)
- [Final Thoughts](https://runcloud.io/blog/bash-for-loop#final-thoughts)
In this article, weâll demystify the âforâ loop in Bash scripting. Whether youâre a developer, sysadmin, or just curious about the command line, understanding âforâ loops is essential.
## **Why Are âForâ Loops Necessary?**
The â**forâ loop** is a fundamental construct that allows you to repeat a set of commands or actions multiple times. Itâs like having a trusty assistant who diligently performs a task for you over and over again. Whether youâre processing files, managing directories, or automating tasks, there are many scenarios when loops are useful:
1. **File Processing and Batch Operations**:
- Loop through files in a directory to perform batch operations, such as renaming, moving, or compressing them.
- Process log files, extract relevant information, and generate reports.
2. **System Administration and Configuration**:
- Iterate over a list of user accounts to apply changes (e.g., setting permissions, updating passwords).
- Configure network interfaces, firewall rules, or services on multiple servers.
3. **Backup and Archiving**:
- Create backup scripts that loop through directories and files to archive or synchronize data.
- Rotate log files by compressing older logs and keeping a specified number of recent ones.
4. **Automating Repetitive Tasks**:
- Run commands on multiple remote servers via SSH.
- Schedule regular tasks (e.g., backups, database maintenance) using cron jobs.
5. **Data Processing and Transformation**:
- Parse CSV files or other structured data formats.
- Transform data (e.g., converting file formats, extracting specific fields).
Loops in general are versatile and can be adapted to various scenarios. They allow you to iterate over lists, directories, or any other collection of items in your scripts.
In this post, weâll explore the basic syntax of âforâ loops, and demonstrate their versatility with practical examples. By the end, youâll be ready to wield this powerful tool in your Linux journey.
***
## Basic Syntax of Bash âForâ Loop
A `'for'` loop is a control structure in programming that allows you to repeat a set of commands for each item in a list. Itâs like a conveyor belt that processes each item one by one.
**Syntax**:
- `for variable in list`: This line initializes a loop. The `variable` represents the current item from the `list`.
- `do`: This marks the beginning of the loop body.
- `# Commands to execute for each item in the list`: Here, you can put any commands or actions you want to perform on each item.
- `done`: This marks the end of the loop.
```
for variable in list
do
# Commands to execute for each item in the list
done
```
**Explanation**:
- You define a `variable` (usually a single letter) to keep track of the current item.
- The `list` contains multiple items (e.g., filenames, numbers, or strings).
- For each item in the `list`, the commands inside the loop are executed.
- Once all items are processed, the loop ends.
**Execution Frequency**:
- The `for` loop executes once for each item in the specified `list`.
- If there are **n** items in the list, the loop will run **n** times.
- For example, if you have a list of three filenames (`file1.txt`, `file2.txt`, and `file3.txt`), the loop will execute three times, once for each filename.
```
for filename in file1.txt file2.txt file3.txt
do
if [ "$filename" == "file2.txt" ]; then
echo "Found file2.txt! Exiting loop."
break
fi
echo "Processing $filename"
done
```

## Using Bash âForâ Loop
### Looping through Files and Directories
You can use a `'for'` loop to process files or directories. This is ideal if you want to traverse through a directory which has a large number of files, or if the number of files keep changing.
```
#!/bin/bash
for file in /path/to/files/*; do
echo "Processing file: $file"
# Add your custom commands here
done
```

### Iterating over a Range of Numbers
To loop through a range of numbers, use the `{start..end}` notation. If you want to run the loop a fixed number of times, you can create a list of numbers using this format.
```
#!/bin/bash
for i in {1..5}; do
echo "Number: $i"
done
```

### Using âforâ with Command Substitution
The âforâ loop is flexible and powerful. You can redirect the output of other commands in the loop, and then process each item in the list.
```
#!/bin/bash
for user in $(cut -d: -f1 /etc/passwd); do
echo "User: $user"
done
```

### Nested âforâ Loops
If a simple âforâ loop isnât enough, you can use multiple âforâ loops together to achieve more complex functionality.
```
#!/bin/bash
for outer in A B C; do
for inner in 1 2 3; do
echo "$outer->$inner"
done
done
```

## **Final Thoughts**
Youâve now unlocked the potential of **Bash for loops**. It is like a Swiss Army knife for your command line adventures. Mastering the âforâ loop opens up endless possibilities for automating tasks and managing data efficiently in your Linux environment.
Remember, the command line need not be intimidating, but if you do find it a bit daunting then you should check out **[RunCloud](https://runcloud.io/)**, a web platform to manage your servers that **works with any cloud provider**. [Sign up for RunCloud](https://manage.runcloud.io/auth/onboard) and experience the best of both worlds:
- **Web-Friendly Dashboard**: Get started quickly without diving into complex Linux commands. RunCloud provides an intuitive interface for managing your servers.
- **Command Line Freedom**: If youâre a terminal enthusiast, RunCloud gives you the flexibility to tinker with the command line whenever you wish. |
| Shard | 143 (laksa) |
| Root Hash | 15992561546915991943 |
| Unparsed URL | io,runcloud!/blog/bash-for-loop s443 |