ℹ️ 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://ostechnix.com/bash-for-loop-shell-scripting/ |
| Last Crawled | 2026-04-15 08:19:37 (8 hours ago) |
| First Indexed | 2021-09-21 12:29:01 (4 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Bash For Loop Explained With Examples - OSTechNix |
| Meta Description | Loops are useful for automating repetitive tasks in Bash shell scripting. In this guide, we will learn about Bash for loop with examples. |
| Meta Canonical | null |
| Boilerpipe Text | In Bash shell scripting, Loops are useful for automating repetitive tasks. When you have to repeat a task N number of times in your script, loops should be used. There are three types of loops supported in bash.
For loop
While loop
Until loop
All three loops serve the same purpose of repeating the task N number of times when a condition is satisfied but with differences in how they are defined and used to achieve the result.
This article will focus on
"for loop" in Bash scripting
. We will learn about the other two loops in our next guide.
Table of Contents
For loop syntax
Example 1 – Working with list of items
Example 2 – Working with ranges
Example 3 – Running commands
Example 4 – Loop over array elements
Example 5 – C style for loop syntax
Example 6 – Break, Continue statement usage
Example 7 – True statement usage
Conclusion
For loop syntax
Understanding syntax is very important before you write your first
for loop
.
for NAME in [ LIST OF ITEMS ]
do
Command 1
Command 2
.....
Command N
done
Let's break it down and see what it does.
Start with the keyword
"for"
followed by a variable name.
The keyword
"in"
get the list of items and store it in the variable for each iteration.
The keyword
"do"
and
"done"
marks the start and end of the loop block and the command should be written within do and done.
There are no strict indentation rules but for better readability use
2 spaces
or
tab(4)
. Be consistent in using either space or tab throughout your script.
You can also create a single line for loops. Create a
for loop
in the terminal and press the up arrow key and you will see bash automatically converts it into a single line loop.
for NAME in [ LIST OF ITEMS]; do COMMANDS ; done
Example 1 - Working with list of items
Let’s start with a simple example.
From the previous section, you might have understood that the
for loop
accepts a list of items. The list of items can be anything like strings, arrays, integers, ranges, command output, etc.
Open the terminal and run the following piece of code.
N=1
for val in Welcome To Ostechnix
do
echo "Iteration $N → $val"
((++N))
done
Let's break it down.
"Welcome to Ostechnix"
is the list of items passed to the
for loop
and each word will be picked as a separate iteration and stored in a variable (
val
).
The variable can be named anything. Here I name it as
val
.
There are three items in the list so there will be three iterations in the
for loop
and each time the value of variable
val
is printed.
The command
((
++N
))
will act as a counter and increment the variable value
N
so it can be printed in the
echo
statement.
for loop example
Now after running the above
for loop
command press the up arrow key from the terminal and you can see the multi-line
for loop
is converted to a single line for a loop.
Example 2 - Working with ranges
You may want to run the
for loop
N
number of times, for that, you can use bash built-in sequence generator
"{x..y[..incr]}"
which will generate a sequence of numbers.
X
= Starting Integer value
Y
= Ending Integer value
Incr
= optional Integer value which does increment of integers
Let’s say you want to run for loop five times then you can use the following snippet.
for rng in {1..5}
do
echo "Value is == $rng"
done
for loop with range
You can also use the optional increment parameter which will do step-wise increments.
Take a look at the below snippet where the increment of three is given. This will generate the sequence from one and do a step increment of three until the end value ten.
for rng1 in {1..10..3}
do
echo "Value is == $rng1"
done
Increment values in for loop
Example 3 - Running commands
You can run any commands that derive a list of items to be processed by
for loop
. The command should be either enclosed with ticks "
``
" or brackets "
$()
".
In the below example, I am running the command that will get process ID and filter the last five processes. For loop will now iterate through each process ID.
for list in $(ps -ef | awk {' print $2 '} | tail -n 5)
do
echo $list
done
Running command in for loop
Example 4 - Loop over array elements
In real-time scenarios, you will store some values in arrays and try to loop over the array for further processing.
Before understanding how to iterate through an array, you have to understand the behavior of two special variables(
$@
and
$*
). Both these are special variables that are used to access all the elements from an array.
Run the following piece of code in the terminal. An array
X
is created and when I try to print all the values (
$X
) like how I print variables, it is just returning the first value from the array.
$ X=( 16 09 2021 "Thursday Third Week" )
$ echo $X
16
Printing array elements
To access all the elements in an array, you either have to use
$@
or
$*
. The syntax for accessing array values will be as follows.
$ echo ${X[@]}
16 09 2021 Thursday Third Week
$ echo ${X[*]}
16 09 2021 Thursday Third Week
Array expansion
Now use this with
for loop
to iterate through the array values.
X=( 16 09 2021 "Thursday Third Week" )
for items in ${X[@]}
do
echo $items
done
Looping through array elements
Take a look at the above output. This output seems to be wrong, because the string (Thursday Third Week) inside the array should be considered as a single value. But here each item is treated as a separate item.
This is the default behavior when you use
$@
or
$
. To overcome this, enclose the array expansion variable (
$@
or
$
) in double-quotes.
for items in "${X[@]}"
do
echo $items
done
Usage of double quotes with $@ in for loop
When you use double quotes,
$@
and
$*
behave differently. While
$@
expands the array to each item in an array-like as shown in the above example,
$*
will expand the entire array as one value.
for items in "${X[*]}"
do
echo $items
done
Usage of double quotes with $* in for loop
Heads Up:
Both
$@
and
$*
behave identically unless it is enclosed with
double-quotes
. Try to avoid
$*
unless it is needed.
Example 5 - C style for loop syntax
Bash also offers
c
style
for loop
syntax. If are from a
C
language background, then this syntax will not be new to you.
Instead of iterating through a list, you will be evaluating a condition and if the condition is true, the commands within the loop will be executed.
There are three parameters that you have to understand in this syntax.
Variable
- A variable is initialized only once when the loop is triggered.
Condition
- Condition should be true for the loop to be executed else the loop will not run.
Counter
- This will increment the variable value.
Each parameter should be separated by a
semicolon
(
;
) and should be enclosed in
double brackets
as shown below.
for (( variable; condition; counter ))
do
Command 1
Command 2
Command N
done
Take a look at the below leap year example.
The variable
YEAR=2010
will be first initialized.
The condition
YEAR<=20
will be evaluated and if it is true the code between
do
and the
done
block will be executed.
The counter
YEAR++
will increment the year by one count. Till the variable
YEAR
is incremented to
2020
, the loop will iterate.
Within
do
and
done
block, conditional statement is written to check if the year is a leap year or not.
for ((YEAR=2010; YEAR<=2020; YEAR++))
do
if [[ $(expr $YEAR % 4) -eq 0 ]]
then
echo "$YEAR = leap year"
else
echo "$YEAR = not a leap year"
fi
done
Find leap year with for loop statement
Example 6 - Break, Continue statement usage
There are two bash built-in keywords that are used to control the flow of your loops.
Break
- Exits the loop and skip any pending iterations.
Continue
- Skip the current iteration and pass the control back to the for loop to execute the next iteration.
To check if they are bash built-in or not, use
type
command:
$ type break continue
break is a shell builtin
continue is a shell builtin
Let’s see in brief how and where both break and to continue can be used.
I am using the same code I used in the previous section to find the leap year. In this case, I just need what will be the first leap year between 2010 and 2020. If that year is found, my loop can exit.
for ((YEAR=2010; YEAR<=2020; YEAR++))
do
if [[ $(expr $YEAR % 4) -eq 0 ]]
then
echo "$YEAR = leap year"
break
else
echo "$YEAR = not a leap year"
fi
done
Break statement with for loop
From the above output, you can see
for loop
iterates, and when the first leap year 2012 is found,
break
statement is read and the loop is exited and control is given back to the terminal.
Now I am altering the same code for the
"continue"
statement. The
continue
statement when it is interpreted it will skip the current iteration i.e whatever code that comes after continue statement and pass the control back to
for loop
to run the next iteration.
for ((YEAR=2010; YEAR<=2020; YEAR++))
do
if [[ $(expr $YEAR % 4) -eq 0 ]]
then
echo "$YEAR = leap year"
else
continue
echo "$YEAR = not a leap year"
fi
done
Continue statement with for loop
From the above image, you can see there is an echo statement that is skipped by the continue statement.
Example 7 - True statement usage
When you create loops or conditional statements, you cannot leave the block of code empty. Bash will throw a syntax error.
Syntax error
Empty conditional statements
Take a look at both the above images. In the first image, I created a
for loop
but no commands between
do
and
done
. Similarly in the second image, I left the else clause empty. In both cases, bash is not accepting empty blocks and throws syntax errors.
You can use bash builtin
“true"
keyword which will be always set the exit code to
0
(success).
$ type true
true is a shell builtin
In this way, you are leaving the code block kind of empty without bash throwing any errors.
True keyword
Conclusion
In this guide, we have started with the introduction to loops and syntax of
for loop
along with C style. We have also seen how to use
bash for loops
in different conditions along with loop control statements break and continue. Check our next guide to learn about Bash
While
and
Until
loops with examples.
Bash Scripting – While And Until Loop Explained With Examples
Karthick
Karthick is a passionate software engineer who loves to explore new technologies. He is a public speaker and loves writing about technology especially about Linux and opensource. |
| Markdown | - [Home](https://ostechnix.com/)
- [Open Source](https://ostechnix.com/category/opensource/)
- [Technology](https://ostechnix.com/category/technology/)
- [Linux](https://ostechnix.com/category/linux/)
- [Unix](https://ostechnix.com/category/unix/)
- [Donate](https://ostechnix.com/donate/)
- [Contact Us](https://ostechnix.com/contact-us/)
- [About](https://ostechnix.com/about/)
[](https://ostechnix.com/)
- [Home](https://ostechnix.com/)
- [Backup tools](https://ostechnix.com/category/backup-tools/)
- [Command line utilities](https://ostechnix.com/category/command-line-utilities/)
- [Database](https://ostechnix.com/category/database/)
- [DevOps](https://ostechnix.com/category/devops/)
- [Mobile](https://ostechnix.com/category/mobile/)
- [Programming](https://ostechnix.com/category/programming/)
- [Security](https://ostechnix.com/category/security/)
- [Virtualization](https://ostechnix.com/category/virtualization/)
[Home](https://ostechnix.com/) [Bash scripting](https://ostechnix.com/category/bash/bash-scripting/)Bash Scripting – For Loop Explained With Examples
[Bash scripting](https://ostechnix.com/category/bash/bash-scripting/)[BASH](https://ostechnix.com/category/bash/)[Linux](https://ostechnix.com/category/linux/)[Linux Basics](https://ostechnix.com/category/linux-basics/)[Linux Commands](https://ostechnix.com/category/linux-commands/)[Linux Tips & Tricks](https://ostechnix.com/category/linux-tips-tricks/)[Scripting](https://ostechnix.com/category/scripting/)[Shell Scripts](https://ostechnix.com/category/scripting/shell-scripts/)[Unix/Linux Beginners](https://ostechnix.com/category/unixlinux-beginners/)
# Bash Scripting – For Loop Explained With Examples
By [Karthick](https://ostechnix.com/author/karthick/)
Published: September 21, 2021
Written by [Karthick](https://ostechnix.com/author/karthick/)
**Published:**
September 21, 2021
**Updated:**
September 30, 2022
*6\.8K* views
0 comments 9[Facebook](https://www.facebook.com/sharer/sharer.php?u=https://ostechnix.com/bash-for-loop-shell-scripting/)[Twitter](https://x.com/intent/tweet?text=Check%20out%20this%20article:%20Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples%20-%20https://ostechnix.com/bash-for-loop-shell-scripting/)[Linkedin](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fostechnix.com%2Fbash-for-loop-shell-scripting%2F&title=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples)[Reddit](https://reddit.com/submit?url=https%3A%2F%2Fostechnix.com%2Fbash-for-loop-shell-scripting%2F&title=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples)[Whatsapp](https://api.whatsapp.com/send?text=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples%20%0A%0A%20https%3A%2F%2Fostechnix.com%2Fbash-for-loop-shell-scripting%2F)[Telegram](https://telegram.me/share/url?url=https%3A%2F%2Fostechnix.com%2Fbash-for-loop-shell-scripting%2F&text=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples)[Email](mailto:?subject=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples&BODY=https://ostechnix.com/bash-for-loop-shell-scripting/)
*6\.8K*
In Bash shell scripting, Loops are useful for automating repetitive tasks. When you have to repeat a task N number of times in your script, loops should be used. There are three types of loops supported in bash.
1. For loop
2. While loop
3. Until loop
All three loops serve the same purpose of repeating the task N number of times when a condition is satisfied but with differences in how they are defined and used to achieve the result.
This article will focus on **"for loop" in Bash scripting**. We will learn about the other two loops in our next guide.
Table of Contents
- [For loop syntax](https://ostechnix.com/bash-for-loop-shell-scripting/#For_loop_syntax "For loop syntax")
- [Example 1 – Working with list of items](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_1_%E2%80%93_Working_with_list_of_items "Example 1 – Working with list of items")
- [Example 2 – Working with ranges](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_2_%E2%80%93_Working_with_ranges "Example 2 – Working with ranges")
- [Example 3 – Running commands](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_3_%E2%80%93_Running_commands "Example 3 – Running commands")
- [Example 4 – Loop over array elements](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_4_%E2%80%93_Loop_over_array_elements "Example 4 – Loop over array elements")
- [Example 5 – C style for loop syntax](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_5_%E2%80%93_C_style_for_loop_syntax "Example 5 – C style for loop syntax")
- [Example 6 – Break, Continue statement usage](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_6_%E2%80%93_Break_Continue_statement_usage "Example 6 – Break, Continue statement usage")
- [Example 7 – True statement usage](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_7_%E2%80%93_True_statement_usage "Example 7 – True statement usage")
- [Conclusion](https://ostechnix.com/bash-for-loop-shell-scripting/#Conclusion "Conclusion")
## For loop syntax
Understanding syntax is very important before you write your first `for loop`.
```
for NAME in [ LIST OF ITEMS ]
do
Command 1
Command 2
.....
Command N
done
```
Let's break it down and see what it does.
- Start with the keyword `"for"` followed by a variable name.
- The keyword `"in"` get the list of items and store it in the variable for each iteration.
- The keyword `"do"` and `"done"` marks the start and end of the loop block and the command should be written within do and done.
- There are no strict indentation rules but for better readability use **2 spaces** or **tab(4)**. Be consistent in using either space or tab throughout your script.
You can also create a single line for loops. Create a `for loop` in the terminal and press the up arrow key and you will see bash automatically converts it into a single line loop.
```
for NAME in [ LIST OF ITEMS]; do COMMANDS ; done
```
## Example 1 - Working with list of items
Let’s start with a simple example.
From the previous section, you might have understood that the `for loop` accepts a list of items. The list of items can be anything like strings, arrays, integers, ranges, command output, etc.
Open the terminal and run the following piece of code.
```
N=1
for val in Welcome To Ostechnix
do
echo "Iteration $N → $val"
((++N))
done
```
Let's break it down.
- `"Welcome to Ostechnix"` is the list of items passed to the `for loop` and each word will be picked as a separate iteration and stored in a variable (`val`).
- The variable can be named anything. Here I name it as `val`.
- There are three items in the list so there will be three iterations in the `for loop` and each time the value of variable `val` is printed.
- The command **((`++N`))** will act as a counter and increment the variable value `N` so it can be printed in the `echo` statement.
[](https://ostechnix.com/wp-content/uploads/2021/09/for-loop-example.png)
for loop example
Now after running the above `for loop` command press the up arrow key from the terminal and you can see the multi-line `for loop` is converted to a single line for a loop.
## Example 2 - Working with ranges
You may want to run the `for loop` **N** number of times, for that, you can use bash built-in sequence generator `"{x..y[..incr]}"` which will generate a sequence of numbers.
- `X` = Starting Integer value
- `Y` = Ending Integer value
- `Incr` = optional Integer value which does increment of integers
Let’s say you want to run for loop five times then you can use the following snippet.
```
for rng in {1..5}
do
echo "Value is == $rng"
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/for-loop-with-range.png)
for loop with range
You can also use the optional increment parameter which will do step-wise increments.
Take a look at the below snippet where the increment of three is given. This will generate the sequence from one and do a step increment of three until the end value ten.
```
for rng1 in {1..10..3}
do
echo "Value is == $rng1"
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Increment-values-in-for-loop.png)
Increment values in for loop
## Example 3 - Running commands
You can run any commands that derive a list of items to be processed by `for loop`. The command should be either enclosed with ticks "` `` `" or brackets "`$()`".
In the below example, I am running the command that will get process ID and filter the last five processes. For loop will now iterate through each process ID.
```
for list in $(ps -ef | awk {' print $2 '} | tail -n 5)
do
echo $list
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Running-command-in-for-loop.png)
Running command in for loop
## Example 4 - Loop over array elements
In real-time scenarios, you will store some values in arrays and try to loop over the array for further processing.
Before understanding how to iterate through an array, you have to understand the behavior of two special variables( `$@` and `$*`). Both these are special variables that are used to access all the elements from an array.
Run the following piece of code in the terminal. An array **X** is created and when I try to print all the values (`$X`) like how I print variables, it is just returning the first value from the array.
```
$ X=( 16 09 2021 "Thursday Third Week" )
```
```
$ echo $X
16
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Printing-array-elements.png)
Printing array elements
To access all the elements in an array, you either have to use `$@` or `$*`. The syntax for accessing array values will be as follows.
```
$ echo ${X[@]}
16 09 2021 Thursday Third Week
```
```
$ echo ${X[*]}
16 09 2021 Thursday Third Week
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Array-expansion.png)
Array expansion
Now use this with `for loop` to iterate through the array values.
```
X=( 16 09 2021 "Thursday Third Week" )
for items in ${X[@]}
do
echo $items
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Looping-through-array-elements.png)
Looping through array elements
Take a look at the above output. This output seems to be wrong, because the string (Thursday Third Week) inside the array should be considered as a single value. But here each item is treated as a separate item.
This is the default behavior when you use `$@` or `$`. To overcome this, enclose the array expansion variable (`$@` or `$`) in double-quotes.
```
for items in "${X[@]}"
do
echo $items
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Usage-of-double-quotes-in-for-loop.png)
Usage of double quotes with \$@ in for loop
When you use double quotes, `$@` and `$*` behave differently. While `$@` expands the array to each item in an array-like as shown in the above example, `$*` will expand the entire array as one value.
```
for items in "${X[*]}"
do
echo $items
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Usage-of-double-quotes-with-in-for-loop.png)
Usage of double quotes with \$\* in for loop
**Heads Up:** Both `$@` and `$*` behave identically unless it is enclosed with **double-quotes**. Try to avoid `$*` unless it is needed.
## Example 5 - C style for loop syntax
Bash also offers **c** style `for loop` syntax. If are from a **C** language background, then this syntax will not be new to you.
Instead of iterating through a list, you will be evaluating a condition and if the condition is true, the commands within the loop will be executed.
There are three parameters that you have to understand in this syntax.
- **Variable** - A variable is initialized only once when the loop is triggered.
- **Condition** - Condition should be true for the loop to be executed else the loop will not run.
- **Counter** - This will increment the variable value.
Each parameter should be separated by a **semicolon** (`;`) and should be enclosed in **double brackets** as shown below.
```
for (( variable; condition; counter ))
do
Command 1
Command 2
Command N
done
```
Take a look at the below leap year example.
- The variable `YEAR=2010` will be first initialized.
- The condition `YEAR<=20` will be evaluated and if it is true the code between `do` and the `done` block will be executed.
- The counter `YEAR++` will increment the year by one count. Till the variable `YEAR` is incremented to `2020`, the loop will iterate.
- Within `do` and `done` block, conditional statement is written to check if the year is a leap year or not.
```
for ((YEAR=2010; YEAR<=2020; YEAR++))
do
if [[ $(expr $YEAR % 4) -eq 0 ]]
then
echo "$YEAR = leap year"
else
echo "$YEAR = not a leap year"
fi
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Find-leap-year-with-for-loop-statement.png)
Find leap year with for loop statement
## Example 6 - Break, Continue statement usage
There are two bash built-in keywords that are used to control the flow of your loops.
- **Break** - Exits the loop and skip any pending iterations.
- **Continue** - Skip the current iteration and pass the control back to the for loop to execute the next iteration.
To check if they are bash built-in or not, use `type` command:
```
$ type break continue
break is a shell builtin
continue is a shell builtin
```
Let’s see in brief how and where both break and to continue can be used.
I am using the same code I used in the previous section to find the leap year. In this case, I just need what will be the first leap year between 2010 and 2020. If that year is found, my loop can exit.
```
for ((YEAR=2010; YEAR<=2020; YEAR++))
do
if [[ $(expr $YEAR % 4) -eq 0 ]]
then
echo "$YEAR = leap year"
break
else
echo "$YEAR = not a leap year"
fi
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Break-statement-with-for-loop.png)
Break statement with for loop
From the above output, you can see `for loop` iterates, and when the first leap year 2012 is found, `break` statement is read and the loop is exited and control is given back to the terminal.
Now I am altering the same code for the `"continue"` statement. The `continue` statement when it is interpreted it will skip the current iteration i.e whatever code that comes after continue statement and pass the control back to `for loop` to run the next iteration.
```
for ((YEAR=2010; YEAR<=2020; YEAR++))
do
if [[ $(expr $YEAR % 4) -eq 0 ]]
then
echo "$YEAR = leap year"
else
continue
echo "$YEAR = not a leap year"
fi
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Continue-statement-with-for-loop.png)
Continue statement with for loop
From the above image, you can see there is an echo statement that is skipped by the continue statement.
## Example 7 - True statement usage
When you create loops or conditional statements, you cannot leave the block of code empty. Bash will throw a syntax error.
[](https://ostechnix.com/wp-content/uploads/2021/09/Syntax-error.png)
Syntax error
[](https://ostechnix.com/wp-content/uploads/2021/09/Empty-conditional-statements.png)
Empty conditional statements
Take a look at both the above images. In the first image, I created a `for loop` but no commands between `do` and `done`. Similarly in the second image, I left the else clause empty. In both cases, bash is not accepting empty blocks and throws syntax errors.
You can use bash builtin `“true"` keyword which will be always set the exit code to **0** (success).
```
$ type true
true is a shell builtin
```
In this way, you are leaving the code block kind of empty without bash throwing any errors.
[](https://ostechnix.com/wp-content/uploads/2021/09/True-keyword.png)
True keyword
## Conclusion
In this guide, we have started with the introduction to loops and syntax of `for loop` along with C style. We have also seen how to use **bash for loops** in different conditions along with loop control statements break and continue. Check our next guide to learn about Bash `While` and `Until` loops with examples.
- **[Bash Scripting – While And Until Loop Explained With Examples](https://ostechnix.com/bash-while-until-loop-shell-scripting/)**
**Related read:**
- **[Bash Scripting – Select Loop Explained With Examples](https://ostechnix.com/bash-select-loop/)**
- **[Bash Scripting – Functions Explained With Examples](https://ostechnix.com/bash-functions-shell-scripting/)**
- **[Bash Scripting – Variables Explained With Examples](https://ostechnix.com/bash-variables-shell-scripting/)**
- **[Bash Echo Command Explained With Examples In Linux](https://ostechnix.com/bash-echo-command-in-linux/)**
- **[Bash Heredoc Tutorial For Beginners](https://ostechnix.com/bash-heredoc-tutorial/)**
- **[Bash Redirection Explained With Examples](https://ostechnix.com/bash-redirection-explained-with-examples/)**
- **[Difference Between Defining Bash Variables With And Without export](https://ostechnix.com/difference-between-defining-bash-variables-with-and-without-export/)**
[BASH](https://ostechnix.com/tag/bash/)[Bash loops](https://ostechnix.com/tag/bash-loops/)[Bash scripting](https://ostechnix.com/tag/bash-scripting/)[for loop](https://ostechnix.com/tag/for-loop/)[Linux](https://ostechnix.com/tag/linux/)[Scripting](https://ostechnix.com/tag/scripting/)[Shell scripting](https://ostechnix.com/tag/shell-scripting/)[shell scripts](https://ostechnix.com/tag/shell-scripts/)
0 comments 9 [Facebook](https://www.facebook.com/sharer/sharer.php?u=https://ostechnix.com/bash-for-loop-shell-scripting/)[Twitter](https://x.com/intent/tweet?text=Check%20out%20this%20article:%20Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples%20-%20https://ostechnix.com/bash-for-loop-shell-scripting/)[Linkedin](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fostechnix.com%2Fbash-for-loop-shell-scripting%2F&title=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples)[Reddit](https://reddit.com/submit?url=https%3A%2F%2Fostechnix.com%2Fbash-for-loop-shell-scripting%2F&title=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples)[Whatsapp](https://api.whatsapp.com/send?text=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples%20%0A%0A%20https%3A%2F%2Fostechnix.com%2Fbash-for-loop-shell-scripting%2F)[Telegram](https://telegram.me/share/url?url=https%3A%2F%2Fostechnix.com%2Fbash-for-loop-shell-scripting%2F&text=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples)[Email](mailto:?subject=Bash%20Scripting%20-%20For%20Loop%20Explained%20With%20Examples&BODY=https://ostechnix.com/bash-for-loop-shell-scripting/)

##### [Karthick](https://ostechnix.com/author/karthick/ "Author Karthick")
Karthick is a passionate software engineer who loves to explore new technologies. He is a public speaker and loves writing about technology especially about Linux and opensource.
Previous post
[How To Identify Operating System Using TTL Value And Ping Command](https://ostechnix.com/identify-operating-system-ttl-ping/)
Next post
[Bash Scripting – While And Until Loop Explained With Examples](https://ostechnix.com/bash-while-until-loop-shell-scripting/)
#### You May Also Like
### [Bash Scripting – Functions Explained With Examples](https://ostechnix.com/bash-functions-shell-scripting/)
Published: September 16, 2021
### [Bash Scripting: Variables Explained With Examples](https://ostechnix.com/bash-variables-shell-scripting/)
Published: September 13, 2021
### [How To Perform Arithmetic Operations In Bash](https://ostechnix.com/bash-arithmetic-operations/)
Published: September 5, 2022
### [Bash Echo Command Explained With Examples In Linux](https://ostechnix.com/bash-echo-command-in-linux/)
Published: September 1, 2021
### [Enhancing SSH Login With A Tmux Session Selection...](https://ostechnix.com/enhancing-ssh-login-with-a-tmux-session-selection-menu/)
Published: October 2, 2023
### [How To Create Interactive Bash Scripts With Yes,...](https://ostechnix.com/create-interactive-bash-scripts-with-yes-no-cancel-prompt/)
Published: July 11, 2024
### Leave a Comment [Cancel Reply](https://ostechnix.com/bash-for-loop-shell-scripting/#respond)
This site uses Akismet to reduce spam. [Learn how your comment data is processed.](https://akismet.com/privacy/)
### Search
### Keep in touch
[Facebook](https://www.facebook.com/ostechnix/) [Twitter](https://twitter.com/ostechnix) [Linkedin](https://in.linkedin.com/in/ostechnix) [Youtube](https://www.youtube.com/channel/UC4GsixqwFwsy95oKhpKIS9g) [Email](mailto:info@ostechnix.com) [Reddit](https://www.reddit.com/r/OSTechNix/) [Rss](https://ostechnix.com/feed/)
#### About OSTechNix
[](https://ostechnix.com/)
OSTechNix (Open Source, Technology, Nix\*) regularly publishes the latest news, how-to articles, tutorials and tips & tricks about free and opensource software and technology.
[Facebook](https://www.facebook.com/ostechnix/) [Twitter](https://twitter.com/ostechnix) [Linkedin](https://in.linkedin.com/in/ostechnix) [Youtube](https://www.youtube.com/channel/UC4GsixqwFwsy95oKhpKIS9g) [Email](mailto:info@ostechnix.com) [Reddit](https://www.reddit.com/r/OSTechNix/) [Rss](https://ostechnix.com/feed/)
Archives
#### Popular Posts
- 1
#### [Yt-dlp Commands: The Complete Tutorial For Beginners (2026)](https://ostechnix.com/yt-dlp-tutorial/ "Yt-dlp Commands: The Complete Tutorial For Beginners (2026)")
Published: September 30, 2023
- 2
#### [Linux Kernel 7.0 is Officially Released: Here’s What’s New](https://ostechnix.com/linux-kernel-7-0-released/ "Linux Kernel 7.0 is Officially Released: Here’s What’s New")
Published: April 14, 2026
- 3
#### [How to Upgrade to Fedora 44 Beta From Fedora 43 Step-by-Step](https://ostechnix.com/upgrade-to-fedora-44-from-fedora-43/ "How to Upgrade to Fedora 44 Beta From Fedora 43 Step-by-Step")
Published: March 11, 2026
- [About](https://ostechnix.com/about/ "About Us")
- [Contact Us](https://ostechnix.com/contact-us/)
- [Privacy Policy](https://ostechnix.com/privacy-policy/)
- [Sitemap](https://ostechnix.com/sitemap/)
- [Terms and Conditions](https://ostechnix.com/terms-and-conditions/)
OSTechNix © 2025. All Rights Reserved. This site is licensed under [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/).
[](https://ostechnix.com/)
- [Home](https://ostechnix.com/)
- [Open Source](https://ostechnix.com/category/opensource/)
- [Technology](https://ostechnix.com/category/technology/)
- [Linux](https://ostechnix.com/category/linux/)
- [Unix](https://ostechnix.com/category/unix/)
- [Donate](https://ostechnix.com/donate/)
- [Contact Us](https://ostechnix.com/contact-us/)
- [About](https://ostechnix.com/about/)
This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. [Accept](https://ostechnix.com/bash-for-loop-shell-scripting/) [Read More](https://ostechnix.com/terms-and-conditions/) |
| Readable Markdown | In Bash shell scripting, Loops are useful for automating repetitive tasks. When you have to repeat a task N number of times in your script, loops should be used. There are three types of loops supported in bash.
1. For loop
2. While loop
3. Until loop
All three loops serve the same purpose of repeating the task N number of times when a condition is satisfied but with differences in how they are defined and used to achieve the result.
This article will focus on **"for loop" in Bash scripting**. We will learn about the other two loops in our next guide.
Table of Contents
- [For loop syntax](https://ostechnix.com/bash-for-loop-shell-scripting/#For_loop_syntax "For loop syntax")
- [Example 1 – Working with list of items](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_1_%E2%80%93_Working_with_list_of_items "Example 1 – Working with list of items")
- [Example 2 – Working with ranges](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_2_%E2%80%93_Working_with_ranges "Example 2 – Working with ranges")
- [Example 3 – Running commands](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_3_%E2%80%93_Running_commands "Example 3 – Running commands")
- [Example 4 – Loop over array elements](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_4_%E2%80%93_Loop_over_array_elements "Example 4 – Loop over array elements")
- [Example 5 – C style for loop syntax](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_5_%E2%80%93_C_style_for_loop_syntax "Example 5 – C style for loop syntax")
- [Example 6 – Break, Continue statement usage](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_6_%E2%80%93_Break_Continue_statement_usage "Example 6 – Break, Continue statement usage")
- [Example 7 – True statement usage](https://ostechnix.com/bash-for-loop-shell-scripting/#Example_7_%E2%80%93_True_statement_usage "Example 7 – True statement usage")
- [Conclusion](https://ostechnix.com/bash-for-loop-shell-scripting/#Conclusion "Conclusion")
## For loop syntax
Understanding syntax is very important before you write your first `for loop`.
```
for NAME in [ LIST OF ITEMS ]
do
Command 1
Command 2
.....
Command N
done
```
Let's break it down and see what it does.
- Start with the keyword `"for"` followed by a variable name.
- The keyword `"in"` get the list of items and store it in the variable for each iteration.
- The keyword `"do"` and `"done"` marks the start and end of the loop block and the command should be written within do and done.
- There are no strict indentation rules but for better readability use **2 spaces** or **tab(4)**. Be consistent in using either space or tab throughout your script.
You can also create a single line for loops. Create a `for loop` in the terminal and press the up arrow key and you will see bash automatically converts it into a single line loop.
```
for NAME in [ LIST OF ITEMS]; do COMMANDS ; done
```
## Example 1 - Working with list of items
Let’s start with a simple example.
From the previous section, you might have understood that the `for loop` accepts a list of items. The list of items can be anything like strings, arrays, integers, ranges, command output, etc.
Open the terminal and run the following piece of code.
```
N=1
for val in Welcome To Ostechnix
do
echo "Iteration $N → $val"
((++N))
done
```
Let's break it down.
- `"Welcome to Ostechnix"` is the list of items passed to the `for loop` and each word will be picked as a separate iteration and stored in a variable (`val`).
- The variable can be named anything. Here I name it as `val`.
- There are three items in the list so there will be three iterations in the `for loop` and each time the value of variable `val` is printed.
- The command **((`++N`))** will act as a counter and increment the variable value `N` so it can be printed in the `echo` statement.
[](https://ostechnix.com/wp-content/uploads/2021/09/for-loop-example.png)
for loop example
Now after running the above `for loop` command press the up arrow key from the terminal and you can see the multi-line `for loop` is converted to a single line for a loop.
## Example 2 - Working with ranges
You may want to run the `for loop` **N** number of times, for that, you can use bash built-in sequence generator `"{x..y[..incr]}"` which will generate a sequence of numbers.
- `X` = Starting Integer value
- `Y` = Ending Integer value
- `Incr` = optional Integer value which does increment of integers
Let’s say you want to run for loop five times then you can use the following snippet.
```
for rng in {1..5}
do
echo "Value is == $rng"
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/for-loop-with-range.png)
for loop with range
You can also use the optional increment parameter which will do step-wise increments.
Take a look at the below snippet where the increment of three is given. This will generate the sequence from one and do a step increment of three until the end value ten.
```
for rng1 in {1..10..3}
do
echo "Value is == $rng1"
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Increment-values-in-for-loop.png)
Increment values in for loop
## Example 3 - Running commands
You can run any commands that derive a list of items to be processed by `for loop`. The command should be either enclosed with ticks "` `` `" or brackets "`$()`".
In the below example, I am running the command that will get process ID and filter the last five processes. For loop will now iterate through each process ID.
```
for list in $(ps -ef | awk {' print $2 '} | tail -n 5)
do
echo $list
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Running-command-in-for-loop.png)
Running command in for loop
## Example 4 - Loop over array elements
In real-time scenarios, you will store some values in arrays and try to loop over the array for further processing.
Before understanding how to iterate through an array, you have to understand the behavior of two special variables( `$@` and `$*`). Both these are special variables that are used to access all the elements from an array.
Run the following piece of code in the terminal. An array **X** is created and when I try to print all the values (`$X`) like how I print variables, it is just returning the first value from the array.
```
$ X=( 16 09 2021 "Thursday Third Week" )
```
```
$ echo $X
16
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Printing-array-elements.png)
Printing array elements
To access all the elements in an array, you either have to use `$@` or `$*`. The syntax for accessing array values will be as follows.
```
$ echo ${X[@]}
16 09 2021 Thursday Third Week
```
```
$ echo ${X[*]}
16 09 2021 Thursday Third Week
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Array-expansion.png)
Array expansion
Now use this with `for loop` to iterate through the array values.
```
X=( 16 09 2021 "Thursday Third Week" )
for items in ${X[@]}
do
echo $items
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Looping-through-array-elements.png)
Looping through array elements
Take a look at the above output. This output seems to be wrong, because the string (Thursday Third Week) inside the array should be considered as a single value. But here each item is treated as a separate item.
This is the default behavior when you use `$@` or `$`. To overcome this, enclose the array expansion variable (`$@` or `$`) in double-quotes.
```
for items in "${X[@]}"
do
echo $items
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Usage-of-double-quotes-in-for-loop.png)
Usage of double quotes with \$@ in for loop
When you use double quotes, `$@` and `$*` behave differently. While `$@` expands the array to each item in an array-like as shown in the above example, `$*` will expand the entire array as one value.
```
for items in "${X[*]}"
do
echo $items
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Usage-of-double-quotes-with-in-for-loop.png)
Usage of double quotes with \$\* in for loop
**Heads Up:** Both `$@` and `$*` behave identically unless it is enclosed with **double-quotes**. Try to avoid `$*` unless it is needed.
## Example 5 - C style for loop syntax
Bash also offers **c** style `for loop` syntax. If are from a **C** language background, then this syntax will not be new to you.
Instead of iterating through a list, you will be evaluating a condition and if the condition is true, the commands within the loop will be executed.
There are three parameters that you have to understand in this syntax.
- **Variable** - A variable is initialized only once when the loop is triggered.
- **Condition** - Condition should be true for the loop to be executed else the loop will not run.
- **Counter** - This will increment the variable value.
Each parameter should be separated by a **semicolon** (`;`) and should be enclosed in **double brackets** as shown below.
```
for (( variable; condition; counter ))
do
Command 1
Command 2
Command N
done
```
Take a look at the below leap year example.
- The variable `YEAR=2010` will be first initialized.
- The condition `YEAR<=20` will be evaluated and if it is true the code between `do` and the `done` block will be executed.
- The counter `YEAR++` will increment the year by one count. Till the variable `YEAR` is incremented to `2020`, the loop will iterate.
- Within `do` and `done` block, conditional statement is written to check if the year is a leap year or not.
```
for ((YEAR=2010; YEAR<=2020; YEAR++))
do
if [[ $(expr $YEAR % 4) -eq 0 ]]
then
echo "$YEAR = leap year"
else
echo "$YEAR = not a leap year"
fi
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Find-leap-year-with-for-loop-statement.png)
Find leap year with for loop statement
## Example 6 - Break, Continue statement usage
There are two bash built-in keywords that are used to control the flow of your loops.
- **Break** - Exits the loop and skip any pending iterations.
- **Continue** - Skip the current iteration and pass the control back to the for loop to execute the next iteration.
To check if they are bash built-in or not, use `type` command:
```
$ type break continue
break is a shell builtin
continue is a shell builtin
```
Let’s see in brief how and where both break and to continue can be used.
I am using the same code I used in the previous section to find the leap year. In this case, I just need what will be the first leap year between 2010 and 2020. If that year is found, my loop can exit.
```
for ((YEAR=2010; YEAR<=2020; YEAR++))
do
if [[ $(expr $YEAR % 4) -eq 0 ]]
then
echo "$YEAR = leap year"
break
else
echo "$YEAR = not a leap year"
fi
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Break-statement-with-for-loop.png)
Break statement with for loop
From the above output, you can see `for loop` iterates, and when the first leap year 2012 is found, `break` statement is read and the loop is exited and control is given back to the terminal.
Now I am altering the same code for the `"continue"` statement. The `continue` statement when it is interpreted it will skip the current iteration i.e whatever code that comes after continue statement and pass the control back to `for loop` to run the next iteration.
```
for ((YEAR=2010; YEAR<=2020; YEAR++))
do
if [[ $(expr $YEAR % 4) -eq 0 ]]
then
echo "$YEAR = leap year"
else
continue
echo "$YEAR = not a leap year"
fi
done
```
[](https://ostechnix.com/wp-content/uploads/2021/09/Continue-statement-with-for-loop.png)
Continue statement with for loop
From the above image, you can see there is an echo statement that is skipped by the continue statement.
## Example 7 - True statement usage
When you create loops or conditional statements, you cannot leave the block of code empty. Bash will throw a syntax error.
[](https://ostechnix.com/wp-content/uploads/2021/09/Syntax-error.png)
Syntax error
[](https://ostechnix.com/wp-content/uploads/2021/09/Empty-conditional-statements.png)
Empty conditional statements
Take a look at both the above images. In the first image, I created a `for loop` but no commands between `do` and `done`. Similarly in the second image, I left the else clause empty. In both cases, bash is not accepting empty blocks and throws syntax errors.
You can use bash builtin `“true"` keyword which will be always set the exit code to **0** (success).
```
$ type true
true is a shell builtin
```
In this way, you are leaving the code block kind of empty without bash throwing any errors.
[](https://ostechnix.com/wp-content/uploads/2021/09/True-keyword.png)
True keyword
## Conclusion
In this guide, we have started with the introduction to loops and syntax of `for loop` along with C style. We have also seen how to use **bash for loops** in different conditions along with loop control statements break and continue. Check our next guide to learn about Bash `While` and `Until` loops with examples.
- **[Bash Scripting – While And Until Loop Explained With Examples](https://ostechnix.com/bash-while-until-loop-shell-scripting/)**

##### [Karthick](https://ostechnix.com/author/karthick/ "Author Karthick")
Karthick is a passionate software engineer who loves to explore new technologies. He is a public speaker and loves writing about technology especially about Linux and opensource. |
| Shard | 40 (laksa) |
| Root Hash | 10538567265436171840 |
| Unparsed URL | com,ostechnix!/bash-for-loop-shell-scripting/ s443 |