ā¹ļø 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 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://phoenixnap.com/kb/bash-for-loop |
| Last Crawled | 2026-04-12 14:09:30 (4 hours ago) |
| First Indexed | 2021-12-15 15:45:16 (4 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Bash Script for Loop Explained with Examples | phoenixNAP KB |
| Meta Description | Learn how to use the Bash script for loop by following the hands-on examples provided in this easy to follow Bash tutorial. |
| Meta Canonical | null |
| Boilerpipe Text | The
for
loop
is an essential programming functionality that goes through a list of elements. For each of those elements, the
for
loop performs a set of commands. The command helps repeat processes until a terminating condition.
Whether you're going through an array of numbers or renaming files,
for
loops in Bash scripts provide a convenient way to list items automatically.
This tutorial shows how to use Bash
for
loops in scripts.
Prerequisites
Access to the terminal/command line (
CTRL
+
ALT
+
T
).
A text editor, such as Nano or Vi/Vim
.
Elementary programming terminology.
Bash Script for Loop
Use the
for
loop to iterate through a list of items to perform the instructed commands.
The basic syntax for the
for
loop in Bash scripts is:
for <element> in <list>
do
<commands>
done
The element, list, and commands parsed through the loop vary depending on the use case.
Bash For Loop Examples
Below are various examples of the
for
loop in Bash scripts. Create a
script
, add the code, and
run the Bash scripts
from the terminal to see the results.
Individual Items
Iterate through a series of given elements and print each with the following syntax:
#!/bin/bash
# For loop with individual numbers
for i in 0 1 2 3 4 5
do
echo "Element $i"
done
Run the script to see the output:
. <script name>
The script prints each element from the provided list to the console.
Alternatively, use strings in a space separated list:
#!/bin/bash
# For loop with individual strings
for i in "zero" "one" "two" "three" "four" "five"
do
echo "Element $i"
done
Save the script and run from the terminal to see the result.
The output prints each element to the console and exits the loop.
Range
Instead of writing a list of individual elements, use the range syntax and indicate the first and last element:
#!/bin/bash
# For loop with number range
for i in {0..5}
do
echo "Element $i"
done
The script outputs all elements from the provided range.
The range syntax also works for letters. For example:
#!/bin/bash
# For loop with letter range
for i in {a..f}
do
echo "Element $i"
done
The script outputs letters to the console in ascending order in the provided range.
The range syntax works for elements in descending order if the starting element is greater than the ending.
For example:
#!/bin/bash
# For loop with reverse number range
for i in {5..0}
do
echo "Element $i"
done
The output lists the numbers in reverse order.
The range syntax works whether elements increase or decrease.
Range with Increment
Use the range syntax and add the step value to go through the range in intervals.
For example, use the following code to list even numbers:
#!/bin/bash
# For loop with range increment numbers
for i in {0..10..2}
do
echo "Element $i"
done
The output prints every other digit from the given range.
Alternatively, loop from ten to zero counting down by even numbers:
#!/bin/bash
# For loop with reverse range increment numbers
for i in {10..0..2}
do
echo "Element $i"
done
Execute the script to print every other element from the range in decreasing order.
Exchange increment
2
for any number less than the distance between the range to get values for different intervals.
The seq Command
The
seq
command generates a number sequence. Parse the sequence in the Bash script
for
loop as a command to generate a list.
For example:
#!/bin/bash
# For loop with seq command
for i in $(seq 0 2 10)
do
echo "Element $i"
done
The output prints each element generated by the
seq
command.
The
seq
command is a historical command and not a recommended way to generate a sequence. The curly braces built-in methods are preferable and faster.
C-Style
Bash scripts allow C-style three parameter
for
loop control expressions. Add the expression between double parentheses as follows:
#!/bin/bash
# For loop C-style
for (( i=0; i<=5; i++ ))
do
echo "Element $i"
done
The expression consists of:
The initializer (
i=0
) determines the number where the loop starts counting.
Stop condition (
i<=5
) indicates when the loop exits.
Step (
i++
) increments the value of
i
until the stop condition.
Separate each condition with a semicolon (
;
). Adjust the three values as needed for your use case.
The terminal outputs each element, starting with the initializer value.
The value increases by the step amount, up to the stop condition.
Infinite Loops
Infinite
for
loops do not have a condition set to terminate the loop. The program runs endlessly because the end condition does not exist or never fulfills.
To generate an infinite
for
loop, add the following code to a Bash script:
#!/bin/bash
# Infinite for loop
for (( ; ; ))
do
echo "CTRL+C to exit"
done
To terminate the script execution, press
CTRL
+
C
.
Infinite loops are helpful when a program runs until a particular condition fulfills.
Break
The
break statement
ends the current loop and helps exit the
for
loop early. This behavior allows exiting the loop before meeting a stated condition.
To demonstrate, add the following code to a Bash script:
#!/bin/bash
# Infinite for loop with break
i=0
for (( ; ; ))
do
echo "Iteration: ${i}"
(( i++ ))
if [[ i -gt 10 ]]
then
break;
fi
done
echo "Done!"
The example shows how to exit an infinite
for
loop using a
break
. The
Bash if statement
helps check the value for each integer and provides the
break
condition. This terminates the script when an integer reaches the value ten.
To exit a nested loop and an outer loop, use
break 2
.
Continue
The
continue
command ends the current loop iteration. The program continues the loop, starting with the following iteration. To illustrate, add the following code to a Bash script to see how the
continue
statement works in a
for
loop:
#!/bin/bash
# For loop with continue statement
for i in {1..100}
do
if [[ $i%11 -ne 0 ]]
then
continue
fi
echo $i
done
The code checks numbers between one and one hundred and prints only numbers divisible by eleven.
The conditional
if
statement checks for divisibility, while the
continue
statement skips any numbers which have a remainder when divided by eleven.
Arrays
Arrays store a list of elements. The
for
loop provides a method to go through arrays by element.
For example, define an array and loop through the elements with:
#!/bin/bash
# For loop with array
array=(1 2 3 4 5)
for i in ${array[@]}
do
echo "Element $i"
done
The output prints each element stored in the array from first to last.
The Bash
for
loop is the only method to iterate through individual array elements.
The
for
loop can also be used to iterate through key-value pairs in associative arrays. For more information, refer to our guide on
associative arrays in Bash
.
Indices
When working with arrays, each element has an index.
List through an array's indices with the following code:
#!/bin/bash
# For loop with array indices
array=(1 2 3 4 5)
for i in ${!array[@]}
do
echo "Array indices $i"
done
Element indexing starts at zero. Therefore, the first element has an index zero.
The output prints numbers from zero to four for an array with five elements.
Nested Loops
To loop through or generate multi-dimensional arrays, use nested
for
loops.
As an example, generate decimal values from zero to three using nested loops:
#!/bin/bash
# Nested for loop
for (( i = 0; i <= 2; i++ ))
do
for (( j = 0 ; j <= 9; j++ ))
do
echo -n " $i.$j "
done
echo ""
done
The code does the following:
Line 1
starts the
for
loop at zero, increments by one, and ends at two, inclusive.
Line 3
starts the nested
for
loop at zero. The value increments by one and ends at nine inclusively.
Line 5
prints the values from the
for
loops. The nested for loops through all numbers three times, once for each outer loop value.
The output prints each number combination to the console and enters a new line when the oute
r
loop finishes one iteration.
Strings
To loop through words in a string, store the string in a variable. Then, parse the variable to a
for
loop as a list.
For example:
#!/bin/bash
# For loop with string
strings="I am a string"
for i in ${strings}
do
echo "String $i"
done
The loop iterates through the string, with each word being a separate element.
The output prints individual words from the string to the console.
Files
The
for
loop combined with proximity searches helps list or alter files that meet a specific condition.
For example, list all Bash scripts in the current directory with a
for
loop:
#!/bin/bash
# For loop with files
for f in *.sh
do
echo $f
done
The script searches through the current directory and lists all files with the
.sh
extension.
Loop through files or directories to automatically rename or change permissions for multiple elements at once.
Command Substitution
The
for
loop accepts command substitution as a list of elements to iterate through.
The next example demonstrates how to write a
for
loop with command substitution:
#!/bin/bash
# For loop with command substitution
list=`cat list.txt`
# Alternatively, use list=$(cat list.txt)
for i in $list
do
echo $i
done
The
Bash comment
offers an alternative syntax for command substitution. The code reads the contents of the
list.txt
file using the
cat
command and saves the information to a variable
list
.
Use the command substitution method to rename files from a list of names saved in a text file.
Command Line Arguments
Use the
for
loop to iterate through command line arguments.
The following example code demonstrates how to read command line arguments in a
for
loop:
#!/bin/bash
# For loop expecting command line arguments
for i in $@
do
echo "$i"
done
Provide the command line arguments when you run the Bash script.
For example:
. <script name> foo bar
The
$@
substitutes each command line argument into the
for
loop.
Conclusion
After following this tutorial, you know how to use the
for
loop in Bash scripts to iterate through lists.
Next, learn how to write and use
Bash functions
.
Was this article helpful?
Yes
No |
| Markdown | - [Call](https://phoenixnap.com/kb/bash-for-loop)
- [Support](tel:1-855-330-1509)
- [Sales](tel:1-877-588-5918)
- [Login](https://phoenixnap.com/kb/bash-for-loop)
- [Bare Metal Cloud](https://bmc.phoenixnap.com/)
- [Admin Hub](https://admin.phoenixnap.com/)
- [Partners](https://phoenixnap.com/partners)
- [COLOCATION](https://phoenixnap.com/colocation)
- [Colocation Premier Carrier Hotel](https://phoenixnap.com/colocation)
- [Data Center as a Service Solutions for Digital Transformation](https://phoenixnap.com/colocation/data-center-as-a-service)
- [Data Center as a Service Overview](https://phoenixnap.com/colocation/data-center-as-a-service)
- [Hardware as a Service Flexible Hardware Leasing](https://phoenixnap.com/colocation/hardware-as-a-service)
- [Bare Metal Cloud API-Driven Dedicated Servers](https://phoenixnap.com/bare-metal-cloud)
- [Object Storage S3 API Compatible Storage Service](https://phoenixnap.com/object-storage)
- [Meet-Me Room The Interconnectivity Hub](https://phoenixnap.com/colocation/meet-me-room)
- [Meet-Me Room Overview](https://phoenixnap.com/colocation/meet-me-room)
- [AWS Direct Connect Dedicated Link to Amazon Cloud](https://phoenixnap.com/colocation/aws-direct-connect)
- [Google Cloud Interconnect Private Connectivity to Google Cloud](https://phoenixnap.com/google-cloud-interconnect)
- [Megaport Cloud Router Simplified Multi-Cloud Connections](https://phoenixnap.com/offers/megaport-cloud-router)
- [All Carriers Global Interconnectivity Options](https://phoenixnap.com/colocation/all-carriers)
- [Schedule a Tour Guided Virtual Data Center Tour](https://phoenixnap.com/phoenix-data-center-virtual-tour)
- [Data Center Locations Global Data Center Footprint](https://phoenixnap.com/colocation/data-center-locations)
- [Data Center Locations Overview](https://phoenixnap.com/colocation/data-center-locations)
- [Phoenix, AZ The Largest Fiber Backbone in the U.S.](https://phoenixnap.com/colocation/phoenix)
- [Amsterdam, NL The Connectivity Hub of Europe](https://phoenixnap.com/colocation/amsterdam)
- [BARE METAL CLOUD](https://phoenixnap.com/bare-metal-cloud)
- [Platform API-Driven Dedicated Servers](https://phoenixnap.com/bare-metal-cloud)
- [Platform Overview](https://phoenixnap.com/bare-metal-cloud)
- [Infrastructure As Code DevOps Integrations](https://phoenixnap.com/bare-metal-cloud/infrastructure-as-code)
- [BMC vs. Dedicated Servers Choose the Best Option](https://phoenixnap.com/bare-metal-cloud-vs-dedicated-servers)
- [Pricing Instance pricing and cost estimation](https://phoenixnap.com/kb/bash-for-loop)
- [Instance Pricing See All Configurations](https://phoenixnap.com/bare-metal-cloud/instances)
- [Pricing Calculator Get an Estimate](https://phoenixnap.com/cloud-pricing-calculator)
- [Network/IP Pricing Flexible IP Pricing](https://phoenixnap.com/bare-metal-cloud/ip-pricing)
- [Kubernetes Solutions Streamlined Kubernetes Management](https://phoenixnap.com/kb/bash-for-loop)
- [Rancher Deployment One-Click Kubernetes Deployment](https://phoenixnap.com/bare-metal-cloud/rancher-deployment)
- [CPUs Next Gen Intel Processors](https://phoenixnap.com/kb/bash-for-loop)
- [Xeon 6 6700-series with E-Cores Supercharge Cloud-Native Workloads](https://phoenixnap.com/bare-metal-cloud/intel-xeon-6-processors-with-e-cores)
- [Intel® Core⢠i9 14900K Ideal for Gaming, Streaming, and Content Creation](https://phoenixnap.com/bare-metal-cloud/intel-core-i9-14900k)
- [5th Gen Intel Xeon Scalable CPUs Boost Data-Intensive Workloads](https://phoenixnap.com/bare-metal-cloud/5th-gen-intel-xeon-scalable-processors)
- [HPE Ampere Altra Q80-30 HPEĀ® ProLiant RL300 as a service](https://phoenixnap.com/bare-metal-cloud/hpe-proliant-rl300)
- [Alliances Technology Partnerships](https://phoenixnap.com/bare-metal-cloud/technology-ecosystem)
- [Ecosystem Underlying Technologies](https://phoenixnap.com/bare-metal-cloud/technology-ecosystem)
- [NetrisOS VPC networking on bare metal](https://phoenixnap.com/bare-metal-cloud/netris)
- [Storage Options Flexible Storage Solutions](https://phoenixnap.com/kb/bash-for-loop)
- [Object Storage S3-Compatible Storage Solution](https://phoenixnap.com/object-storage)
- [Network File Storage All-Flash Scale-Out Storage Resources](https://phoenixnap.com/network-file-storage)
- [GPU Servers For AI/ML and HPC workloads](https://phoenixnap.com/kb/bash-for-loop)
- [Intel Max 1100 GPUs 1 system. 2 GPUs. Amazing performance.](https://phoenixnap.com/bare-metal-cloud/gpu-servers)
- [HYBRID CLOUD](https://phoenixnap.com/security/data-security-cloud)
- [Hybrid Cloud Overview](https://phoenixnap.com/cloud-services/hybrid-cloud-solutions)
- [Object Storage S3 Compatible Storage Solution](https://phoenixnap.com/object-storage)
- [Bare Metal Cloud API-Driven Dedicated Servers](https://phoenixnap.com/bare-metal-cloud)
- [Alternative Cloud Provider Overcome Public Cloud Limitations](https://phoenixnap.com/cloud-services/alternative-cloud-provider)
- [Backup Solutions Veeam-Powered Services](https://phoenixnap.com/backup-restore)
- [Disaster Recovery VMware, Veeam, Zerto](https://phoenixnap.com/disaster-recovery-as-a-service-draas)
- [Veeam Cloud Connect Backup and Replication](https://phoenixnap.com/backup-restore/veeam-cloud-connect)
- [Managed Backup for Microsoft 365 Veeam-Powered Service](https://phoenixnap.com/backup-restore/microsoft-365-backup)
- [NETWORK](https://phoenixnap.com/network)
- [Network Overview Global Network Footprint](https://phoenixnap.com/network)
- [Network Locations U.S., Europe, APAC, LATAM](https://phoenixnap.com/network/locations)
- [Speed Test Download Speed Test](https://phoenixnap.com/network/speed-test)
- [LEARN](https://phoenixnap.com/kb)
- [Blog IT Tips and Tricks](https://phoenixnap.com/blog/)
- [Resource Library Knowledge Resources](https://phoenixnap.com/company/resource-library)
- [Glossary IT Terms and Definitions](https://phoenixnap.com/glossary/)
- [Events Let's Meet\!](https://phoenixnap.com/company/it-events)
- [Newsroom Media Library](https://phoenixnap.com/company/press)
- [Developers Development Resources Portal](https://developers.phoenixnap.com/)
- [APIs Access Our Public APIs](https://developers.phoenixnap.com/apis)
- [GitHub Public Code Repositories](https://github.com/phoenixnap)
[Home](https://phoenixnap.com/) Ā» [KB](https://phoenixnap.com/kb/) Ā» [DevOps and Development](https://phoenixnap.com/kb/category/devops-and-development) Ā» Bash Script for Loop Explained with Examples
# Bash Script for Loop Explained with Examples


By
[Milica Dancuk](https://phoenixnap.com/kb/author/milica-dancuk)
Published:
December 15, 2021
Topics:
[bash](https://phoenixnap.com/kb/tag/bash), [linux](https://phoenixnap.com/kb/tag/linux)
The **`for`** [loop](https://phoenixnap.com/glossary/what-is-a-loop) is an essential programming functionality that goes through a list of elements. For each of those elements, the **`for`** loop performs a set of commands. The command helps repeat processes until a terminating condition.
Whether you're going through an array of numbers or renaming files, **`for`** loops in Bash scripts provide a convenient way to list items automatically.
**This tutorial shows how to use Bash `for` loops in scripts.**


Prerequisites
- Access to the terminal/command line (**CTRL**\+**ALT**\+**T**).
- A text editor, such as Nano or Vi/Vim.
- Elementary programming terminology.
## Bash Script for Loop
Use the **`for`** loop to iterate through a list of items to perform the instructed commands.
The basic syntax for the **`for`** loop in Bash scripts is:
```
for <element> in <list>
do
<commands>
done
```
The element, list, and commands parsed through the loop vary depending on the use case.
## Bash For Loop Examples
Below are various examples of the **`for`** loop in Bash scripts. Create a [script](https://phoenixnap.com/glossary/what-is-a-script), add the code, and [run the Bash scripts](https://phoenixnap.com/kb/run-bash-script) from the terminal to see the results.
### Individual Items
Iterate through a series of given elements and print each with the following syntax:
```
#!/bin/bash
# For loop with individual numbers
for i in 0 1 2 3 4 5
do
echo "Element $i"
done
```


Run the script to see the output:
```
. <script name>
```


The script prints each element from the provided list to the console.
Alternatively, use strings in a space separated list:
```
#!/bin/bash
# For loop with individual strings
for i in "zero" "one" "two" "three" "four" "five"
do
echo "Element $i"
done
```


Save the script and run from the terminal to see the result.


The output prints each element to the console and exits the loop.
### Range
Instead of writing a list of individual elements, use the range syntax and indicate the first and last element:
```
#!/bin/bash
# For loop with number range
for i in {0..5}
do
echo "Element $i"
done
```


The script outputs all elements from the provided range.


The range syntax also works for letters. For example:
```
#!/bin/bash
# For loop with letter range
for i in {a..f}
do
echo "Element $i"
done
```


The script outputs letters to the console in ascending order in the provided range.


The range syntax works for elements in descending order if the starting element is greater than the ending.
For example:
```
#!/bin/bash
# For loop with reverse number range
for i in {5..0}
do
echo "Element $i"
done
```


The output lists the numbers in reverse order.


The range syntax works whether elements increase or decrease.
### Range with Increment
Use the range syntax and add the step value to go through the range in intervals.
For example, use the following code to list even numbers:
```
#!/bin/bash
# For loop with range increment numbers
for i in {0..10..2}
do
echo "Element $i"
done
```


The output prints every other digit from the given range.


Alternatively, loop from ten to zero counting down by even numbers:
```
#!/bin/bash
# For loop with reverse range increment numbers
for i in {10..0..2}
do
echo "Element $i"
done
```


Execute the script to print every other element from the range in decreasing order.


Exchange increment **`2`** for any number less than the distance between the range to get values for different intervals.
### The seq Command
The **`seq`** command generates a number sequence. Parse the sequence in the Bash script **`for`** loop as a command to generate a list.
For example:
```
#!/bin/bash
# For loop with seq command
for i in $(seq 0 2 10)
do
echo "Element $i"
done
```


The output prints each element generated by the **`seq`** command.
The **`seq`** command is a historical command and not a recommended way to generate a sequence. The curly braces built-in methods are preferable and faster.
### C-Style
Bash scripts allow C-style three parameter **`for`** loop control expressions. Add the expression between double parentheses as follows:
```
#!/bin/bash
# For loop C-style
for (( i=0; i<=5; i++ ))
do
echo "Element $i"
done
```


The expression consists of:
- The initializer (**`i=0`**) determines the number where the loop starts counting.
- Stop condition (**`i<=5`**) indicates when the loop exits.
- Step (**`i++`**) increments the value of **`i`** until the stop condition.
Separate each condition with a semicolon (**`;`**). Adjust the three values as needed for your use case.
The terminal outputs each element, starting with the initializer value.


The value increases by the step amount, up to the stop condition.
### Infinite Loops
Infinite **`for`** loops do not have a condition set to terminate the loop. The program runs endlessly because the end condition does not exist or never fulfills.
To generate an infinite **`for`** loop, add the following code to a Bash script:
```
#!/bin/bash
# Infinite for loop
for (( ; ; ))
do
echo "CTRL+C to exit"
done
```


To terminate the script execution, press **CTRL**\+**C**.


Infinite loops are helpful when a program runs until a particular condition fulfills.
### Break
The [break statement](https://phoenixnap.com/kb/bash-break) ends the current loop and helps exit the **`for`** loop early. This behavior allows exiting the loop before meeting a stated condition.
To demonstrate, add the following code to a Bash script:
```
#!/bin/bash
# Infinite for loop with break
i=0
for (( ; ; ))
do
echo "Iteration: ${i}"
(( i++ ))
if [[ i -gt 10 ]]
then
break;
fi
done
echo "Done!"
```


The example shows how to exit an infinite **`for`** loop using a **`break`**. The [Bash if statement](https://phoenixnap.com/kb/bash-if-statement) helps check the value for each integer and provides the **`break`** condition. This terminates the script when an integer reaches the value ten.


To exit a nested loop and an outer loop, use **`break 2`**.
### Continue
The **`continue`** command ends the current loop iteration. The program continues the loop, starting with the following iteration. To illustrate, add the following code to a Bash script to see how the **`continue`** statement works in a **`for`** loop:
```
#!/bin/bash
# For loop with continue statement
for i in {1..100}
do
if [[ $i%11 -ne 0 ]]
then
continue
fi
echo $i
done
```


The code checks numbers between one and one hundred and prints only numbers divisible by eleven.


The conditional **`if`** statement checks for divisibility, while the **`continue`** statement skips any numbers which have a remainder when divided by eleven.
### Arrays
Arrays store a list of elements. The **`for`** loop provides a method to go through arrays by element.
For example, define an array and loop through the elements with:
```
#!/bin/bash
# For loop with array
array=(1 2 3 4 5)
for i in ${array[@]}
do
echo "Element $i"
done
```


The output prints each element stored in the array from first to last.


The Bash **`for`** loop is the only method to iterate through individual array elements.
The **`for`** loop can also be used to iterate through key-value pairs in associative arrays. For more information, refer to our guide on [associative arrays in Bash](https://phoenixnap.com/kb/bash-associative-array).
### Indices
When working with arrays, each element has an index.
List through an array's indices with the following code:
```
#!/bin/bash
# For loop with array indices
array=(1 2 3 4 5)
for i in ${!array[@]}
do
echo "Array indices $i"
done
```


Element indexing starts at zero. Therefore, the first element has an index zero.


The output prints numbers from zero to four for an array with five elements.
### Nested Loops
To loop through or generate multi-dimensional arrays, use nested **`for`** loops.
As an example, generate decimal values from zero to three using nested loops:
```
#!/bin/bash
# Nested for loop
for (( i = 0; i <= 2; i++ ))
do
for (( j = 0 ; j <= 9; j++ ))
do
echo -n " $i.$j "
done
echo ""
done
```


The code does the following:
- **Line 1** starts the **`for`** loop at zero, increments by one, and ends at two, inclusive.
- **Line 3** starts the nested **`for`** loop at zero. The value increments by one and ends at nine inclusively.
- **Line 5** prints the values from the **`for`** loops. The nested for loops through all numbers three times, once for each outer loop value.


The output prints each number combination to the console and enters a new line when the oute**r** loop finishes one iteration.
### Strings
To loop through words in a string, store the string in a variable. Then, parse the variable to a **`for`** loop as a list.
For example:
```
#!/bin/bash
# For loop with string
strings="I am a string"
for i in ${strings}
do
echo "String $i"
done
```


The loop iterates through the string, with each word being a separate element.


The output prints individual words from the string to the console.
### Files
The **`for`** loop combined with proximity searches helps list or alter files that meet a specific condition.
For example, list all Bash scripts in the current directory with a **`for`** loop:
```
#!/bin/bash
# For loop with files
for f in *.sh
do
echo $f
done
```


The script searches through the current directory and lists all files with the *.sh* extension.


Loop through files or directories to automatically rename or change permissions for multiple elements at once.
### Command Substitution
The **`for`**loop accepts command substitution as a list of elements to iterate through.
The next example demonstrates how to write a **`for`** loop with command substitution:
```
#!/bin/bash
# For loop with command substitution
list=`cat list.txt`
# Alternatively, use list=$(cat list.txt)
for i in $list
do
echo $i
done
```


The [Bash comment](https://phoenixnap.com/kb/bash-comment) offers an alternative syntax for command substitution. The code reads the contents of the *list.txt* file using the **`cat`** command and saves the information to a variable **`list`**.


Use the command substitution method to rename files from a list of names saved in a text file.
**Note:** Learn how to use the cat command and for loop to [read files line by line in Bash](https://phoenixnap.com/kb/bash-read-file-line-by-line).
### Command Line Arguments
Use the **`for`** loop to iterate through command line arguments.
The following example code demonstrates how to read command line arguments in a **`for`** loop:
```
#!/bin/bash
# For loop expecting command line arguments
for i in $@
do
echo "$i"
done
```


Provide the command line arguments when you run the Bash script.
For example:
```
. <script name> foo bar
```


The **`$@`** substitutes each command line argument into the **`for`** loop.
Conclusion
After following this tutorial, you know how to use the **`for`** loop in Bash scripts to iterate through lists.
Next, learn how to write and use [Bash functions](https://phoenixnap.com/kb/bash-function).
Was this article helpful?
YesNo
Contents
- [Bash Script for Loop](https://phoenixnap.com/kb/bash-for-loop#Bash_Script_for_Loop)
- [Bash For Loop Examples](https://phoenixnap.com/kb/bash-for-loop#Bash_For_Loop_Examples)
- [Individual Items](https://phoenixnap.com/kb/bash-for-loop#Individual_Items)
- [Range](https://phoenixnap.com/kb/bash-for-loop#Range)
- [Range with Increment](https://phoenixnap.com/kb/bash-for-loop#Range_with_Increment)
- [The seq Command](https://phoenixnap.com/kb/bash-for-loop#The_seq_Command)
- [C-Style](https://phoenixnap.com/kb/bash-for-loop#C-Style)
- [Infinite Loops](https://phoenixnap.com/kb/bash-for-loop#Infinite_Loops)
- [Break](https://phoenixnap.com/kb/bash-for-loop#Break)
- [Continue](https://phoenixnap.com/kb/bash-for-loop#Continue)
- [Arrays](https://phoenixnap.com/kb/bash-for-loop#Arrays)
- [Indices](https://phoenixnap.com/kb/bash-for-loop#Indices)
- [Nested Loops](https://phoenixnap.com/kb/bash-for-loop#Nested_Loops)
- [Strings](https://phoenixnap.com/kb/bash-for-loop#Strings)
- [Files](https://phoenixnap.com/kb/bash-for-loop#Files)
- [Command Substitution](https://phoenixnap.com/kb/bash-for-loop#Command_Substitution)
- [Command Line Arguments](https://phoenixnap.com/kb/bash-for-loop#Command_Line_Arguments)
Subscribe to our newsletter
[SUBSCRIBE](https://phoenixnap.com/developers-monthly-newsletter)
Next you should read
[](https://phoenixnap.com/kb/bash-check-if-file-directory-exists)
[DevOps and Development](https://phoenixnap.com/kb/category/devops-and-development) [SysAdmin](https://phoenixnap.com/kb/category/sysadmin)
[How To Check If File or Directory Exists in Bash](https://phoenixnap.com/kb/bash-check-if-file-directory-exists)
[](https://phoenixnap.com/kb/change-bash-prompt-linux)
[SysAdmin](https://phoenixnap.com/kb/category/sysadmin) [Web Servers](https://phoenixnap.com/kb/category/web-servers)
[How To Customize Bash Prompt in Linux](https://phoenixnap.com/kb/change-bash-prompt-linux)
[](https://phoenixnap.com/kb/bash-wait-command)
[DevOps and Development](https://phoenixnap.com/kb/category/devops-and-development) [SysAdmin](https://phoenixnap.com/kb/category/sysadmin)
[Bash wait Command with Examples](https://phoenixnap.com/kb/bash-wait-command)
[](https://phoenixnap.com/kb/bash-if-statement)
[DevOps and Development](https://phoenixnap.com/kb/category/devops-and-development) [SysAdmin](https://phoenixnap.com/kb/category/sysadmin)
[Bash if elif else Statement: A Comprehensive Tutorial](https://phoenixnap.com/kb/bash-if-statement)
CONTACT US
[Get a Quote](https://phoenixnap.com/contact-us)
[Support (1-855-330-1509)](tel:1-855-330-1509)
[Sales (1-877-588-5918)](tel:1-877-588-5918)
- [Colocation](https://phoenixnap.com/colocation)
- [Phoenix](https://phoenixnap.com/colocation/phoenix)
- [Ashburn](https://phoenixnap.com/colocation/ashburn)
- [Amsterdam](https://phoenixnap.com/colocation/amsterdam)
- [Atlanta](https://phoenixnap.com/colocation/atlanta)
- [Belgrade](https://phoenixnap.com/colocation/belgrade)
- [Singapore](https://phoenixnap.com/colocation/singapore)
- [Shipping Instructions](https://phoenixnap.com/colocation/shipping-instructions)
RECENT POSTS
[jq Command: How to Process and Transform JSON Data](https://phoenixnap.com/kb/jq)
[ModuleNotFoundError in Python: Causes and Solutions](https://phoenixnap.com/kb/module-not-found-error-python)
[Kill Screen Session in Linux, macOS, Windows](https://phoenixnap.com/kb/kill-screen-session)
[Append Dictionary to Dictionary in Python](https://phoenixnap.com/kb/python-merge-dictionaries)
["Invalid Reference Format" Error in Docker: How to Fix](https://phoenixnap.com/kb/docker-invalid-reference-format)
- [Servers](https://phoenixnap.com/servers/dedicated)
- [Bare Metal Cloud](https://phoenixnap.com/bare-metal-cloud)
- [Dedicated Servers](https://phoenixnap.com/servers/dedicated)
- [Database Servers](https://phoenixnap.com/servers/database)
- [Virtualization Servers](https://phoenixnap.com/servers/virtualization)
- [High Performance Computing (HPC) Servers](https://phoenixnap.com/servers/high-performance-computing-hpc)
- [Dedicated Streaming Servers](https://phoenixnap.com/servers/streaming)
- [Dedicated Game Servers](https://phoenixnap.com/servers/dedicated-game-servers)
- [Dedicated Storage Servers](https://phoenixnap.com/servers/storage)
- [SQL Server Hosting](https://phoenixnap.com/servers/sql-server-hosting)
- [Dedicated Servers in Amsterdam](https://phoenixnap.com/dedicated-servers-amsterdam-netherlands)
- [Cloud Servers in Europe](https://phoenixnap.com/cloud-services/cloud-servers-europe)
- [Big Memory Infrastructure](https://phoenixnap.com/bare-metal-cloud/big-memory-infrastructure)
- [Buy Now](https://admin.phoenixnap.com/wap-pncpadmin-shell/orderForm?bmbPath=/order-form?currencyCode=usd)
- [BMC portal](https://signup.bmc.phoenixnap.com/)
CLOUD SERVICES
- [Data Security Cloud](https://phoenixnap.com/security/data-security-cloud)
- [Managed Private Cloud](https://phoenixnap.com/private)
- [Object Storage](https://phoenixnap.com/object-storage)
- [Solutions](https://phoenixnap.com/infrastructure-solutions)
- [Disaster Recovery](https://phoenixnap.com/infrastructure-solutions/disaster-recovery-services)
- [Web Hosting Reseller](https://phoenixnap.com/reseller-hosting)
- [SaaS Hosting](https://phoenixnap.com/infrastructure-solutions/saas-hosting)
COMPLIANCE
- [HIPAA Ready Hosting](https://phoenixnap.com/compliance/hipaa-compliant-hosting)
- [PCI Compliant Hosting](https://phoenixnap.com/compliance/pci-compliant-hosting)
- [Privacy Center](https://phoenixnap.com/)
- [Do not sell or share my personal information](https://phoenixnap.com/)
NEEDS
- [Disaster Recovery Solutions](https://phoenixnap.com/infrastructure-solutions/disaster-recovery-services)
- [High Availability Solutions](https://phoenixnap.com/infrastructure-solutions/high-availability-solutions)
- [Cloud Evaluation](https://phoenixnap.com/offers/cloud-evaluation-demo)
INDUSTRIES
- [Web Hosting Providers](https://phoenixnap.com/reseller-hosting)
- [Legal](https://phoenixnap.com/infrastructure-solutions/legal-it)
- [MSPs & VARs](https://phoenixnap.com/infrastructure-solutions/it-partners)
- [Media Hosting](https://phoenixnap.com/infrastructure-solutions/media-hosting)
- [Online Gaming](https://phoenixnap.com/infrastructure-solutions/online-gaming)
- [SaaS Hosting Solutions](https://phoenixnap.com/infrastructure-solutions/saas-hosting)
- [Ecommerce Hosting Solutions](https://phoenixnap.com/infrastructure-solutions/ecommerce-hosting)
COMPANY
- [About phoenixNAP](https://phoenixnap.com/about)
- [IaaS Solutions](https://phoenixnap.com/company/iaas-provider)
- [Customer Experience](https://phoenixnap.com/company/customer-experience)
- [Platform](https://phoenixnap.com/cloud-services/platform)
- [Schedule Virtual Tour](https://phoenixnap.com/phoenix-data-center-virtual-tour)
- [Open Source Community](https://phoenixnap.com/company/open-source-community)
- [Resource Library](https://phoenixnap.com/company/resource-library)
- [Press](https://phoenixnap.com/company/press)
- [Events](https://phoenixnap.com/company/it-events)
- [Careers](https://techjobs.dev/jobs/)
- [Promotions](https://phoenixnap.com/promotions)
- [Contact Us](https://phoenixnap.com/contact-us)
- [Legal](https://phoenixnap.com/cs/legal/)
- [Privacy Policy](https://phoenixnap.com/infrastructure-solutions/legal-it/eu-u-s-data-privacy-framework-program-eu-u-s-dpf-compliant-privacy-policy)
- [Terms of Use](https://phoenixnap.com/cs/legal/aup.html)
- [DMCA](https://phoenixnap.com/cs/legal/dmca.html)
- [GDPR](https://phoenixnap.com/gdpr)
- [Sitemap](https://phoenixnap.com/sitemap)
- [Blog](https://phoenixnap.com/blog)
- [Resources](https://phoenixnap.com/company/resource-library)
- [Knowledge Base](https://phoenixnap.com/kb)
- [IT Glossary](https://phoenixnap.com/glossary)
- [GitHub](https://github.com/phoenixnap)
- [RFP Template](https://phoenixnap.com/company/it-resources/data-center-rfp-template)
Ā© 2025 phoenixNAP \| Global IT Services. All Rights Reserved. |
| Readable Markdown | The **`for`** [loop](https://phoenixnap.com/glossary/what-is-a-loop) is an essential programming functionality that goes through a list of elements. For each of those elements, the **`for`** loop performs a set of commands. The command helps repeat processes until a terminating condition. Whether you're going through an array of numbers or renaming files, **`for`** loops in Bash scripts provide a convenient way to list items automatically. **This tutorial shows how to use Bash `for` loops in scripts.**  Prerequisites Access to the terminal/command line (**CTRL**\+**ALT**\+**T**). A text editor, such as Nano or Vi/Vim. Elementary programming terminology. Bash Script for Loop Use the **`for`** loop to iterate through a list of items to perform the instructed commands. The basic syntax for the **`for`** loop in Bash scripts is: The element, list, and commands parsed through the loop vary depending on the use case. Bash For Loop Examples Below are various examples of the **`for`** loop in Bash scripts. Create a [script](https://phoenixnap.com/glossary/what-is-a-script), add the code, and [run the Bash scripts](https://phoenixnap.com/kb/run-bash-script) from the terminal to see the results. Individual Items Iterate through a series of given elements and print each with the following syntax:  Run the script to see the output:  The script prints each element from the provided list to the console. Alternatively, use strings in a space separated list:  Save the script and run from the terminal to see the result.  The output prints each element to the console and exits the loop. Range Instead of writing a list of individual elements, use the range syntax and indicate the first and last element:  The script outputs all elements from the provided range.  The range syntax also works for letters. For example:  The script outputs letters to the console in ascending order in the provided range.  The range syntax works for elements in descending order if the starting element is greater than the ending. For example:  The output lists the numbers in reverse order.  The range syntax works whether elements increase or decrease. Range with Increment Use the range syntax and add the step value to go through the range in intervals. For example, use the following code to list even numbers:  The output prints every other digit from the given range.  Alternatively, loop from ten to zero counting down by even numbers:  Execute the script to print every other element from the range in decreasing order.  Exchange increment **`2`** for any number less than the distance between the range to get values for different intervals. The seq Command The **`seq`** command generates a number sequence. Parse the sequence in the Bash script **`for`** loop as a command to generate a list. For example:  The output prints each element generated by the **`seq`** command. The **`seq`** command is a historical command and not a recommended way to generate a sequence. The curly braces built-in methods are preferable and faster. C-Style Bash scripts allow C-style three parameter **`for`** loop control expressions. Add the expression between double parentheses as follows:  The expression consists of: The initializer (**`i=0`**) determines the number where the loop starts counting. Stop condition (**`i<=5`**) indicates when the loop exits. Step (**`i++`**) increments the value of **`i`** until the stop condition. Separate each condition with a semicolon (**`;`**). Adjust the three values as needed for your use case. The terminal outputs each element, starting with the initializer value.  The value increases by the step amount, up to the stop condition. Infinite Loops Infinite **`for`** loops do not have a condition set to terminate the loop. The program runs endlessly because the end condition does not exist or never fulfills. To generate an infinite **`for`** loop, add the following code to a Bash script:  To terminate the script execution, press **CTRL**\+**C**.  Infinite loops are helpful when a program runs until a particular condition fulfills. Break The [break statement](https://phoenixnap.com/kb/bash-break) ends the current loop and helps exit the **`for`** loop early. This behavior allows exiting the loop before meeting a stated condition. To demonstrate, add the following code to a Bash script:  The example shows how to exit an infinite **`for`** loop using a **`break`**. The [Bash if statement](https://phoenixnap.com/kb/bash-if-statement) helps check the value for each integer and provides the **`break`** condition. This terminates the script when an integer reaches the value ten.  To exit a nested loop and an outer loop, use **`break 2`**. Continue The **`continue`** command ends the current loop iteration. The program continues the loop, starting with the following iteration. To illustrate, add the following code to a Bash script to see how the **`continue`** statement works in a **`for`** loop:  The code checks numbers between one and one hundred and prints only numbers divisible by eleven.  The conditional **`if`** statement checks for divisibility, while the **`continue`** statement skips any numbers which have a remainder when divided by eleven. Arrays Arrays store a list of elements. The **`for`** loop provides a method to go through arrays by element. For example, define an array and loop through the elements with:  The output prints each element stored in the array from first to last.  The Bash **`for`** loop is the only method to iterate through individual array elements. The **`for`** loop can also be used to iterate through key-value pairs in associative arrays. For more information, refer to our guide on [associative arrays in Bash](https://phoenixnap.com/kb/bash-associative-array). Indices When working with arrays, each element has an index. List through an array's indices with the following code:  Element indexing starts at zero. Therefore, the first element has an index zero.  The output prints numbers from zero to four for an array with five elements. Nested Loops To loop through or generate multi-dimensional arrays, use nested **`for`** loops. As an example, generate decimal values from zero to three using nested loops:  The code does the following: **Line 1** starts the **`for`** loop at zero, increments by one, and ends at two, inclusive. **Line 3** starts the nested **`for`** loop at zero. The value increments by one and ends at nine inclusively. **Line 5** prints the values from the **`for`** loops. The nested for loops through all numbers three times, once for each outer loop value.  The output prints each number combination to the console and enters a new line when the oute**r** loop finishes one iteration. Strings To loop through words in a string, store the string in a variable. Then, parse the variable to a **`for`** loop as a list. For example:  The loop iterates through the string, with each word being a separate element.  The output prints individual words from the string to the console. Files The **`for`** loop combined with proximity searches helps list or alter files that meet a specific condition. For example, list all Bash scripts in the current directory with a **`for`** loop:  The script searches through the current directory and lists all files with the *.sh* extension.  Loop through files or directories to automatically rename or change permissions for multiple elements at once. Command Substitution The **`for`**loop accepts command substitution as a list of elements to iterate through. The next example demonstrates how to write a **`for`** loop with command substitution:  The [Bash comment](https://phoenixnap.com/kb/bash-comment) offers an alternative syntax for command substitution. The code reads the contents of the *list.txt* file using the **`cat`** command and saves the information to a variable **`list`**.  Use the command substitution method to rename files from a list of names saved in a text file. Command Line Arguments Use the **`for`** loop to iterate through command line arguments. The following example code demonstrates how to read command line arguments in a **`for`** loop:  Provide the command line arguments when you run the Bash script. For example:  The **`$@`** substitutes each command line argument into the **`for`** loop. Conclusion After following this tutorial, you know how to use the **`for`** loop in Bash scripts to iterate through lists. Next, learn how to write and use [Bash functions](https://phoenixnap.com/kb/bash-function). Was this article helpful? YesNo |
| Shard | 39 (laksa) |
| Root Hash | 8557101678125738839 |
| Unparsed URL | com,phoenixnap!/kb/bash-for-loop s443 |