🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 40 (from laksa169)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

đź“„
INDEXABLE
âś…
CRAWLED
8 hours ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://ostechnix.com/bash-for-loop-shell-scripting/
Last Crawled2026-04-15 08:19:37 (8 hours ago)
First Indexed2021-09-21 12:29:01 (4 years ago)
HTTP Status Code200
Meta TitleBash For Loop Explained With Examples - OSTechNix
Meta DescriptionLoops are useful for automating repetitive tasks in Bash shell scripting. In this guide, we will learn about Bash for loop with examples.
Meta Canonicalnull
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/) [![OSTechNix](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzNTAiIGhlaWdodD0iNzMiIHZpZXdCb3g9IjAgMCAzNTAgNzMiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9IiNjZmQ0ZGIiLz48L3N2Zz4=)](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. [![for loop example](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MTIiIGhlaWdodD0iNDIxIiB2aWV3Qm94PSIwIDAgOTEyIDQyMSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![for loop with range](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2OTQiIGhlaWdodD0iMjg3IiB2aWV3Qm94PSIwIDAgNjk0IDI4NyI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Increment values in for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NTYiIGhlaWdodD0iMjUwIiB2aWV3Qm94PSIwIDAgNjU2IDI1MCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Running command in for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI4NDkiIGhlaWdodD0iMjg5IiB2aWV3Qm94PSIwIDAgODQ5IDI4OSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Printing array elements](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3NzUiIGhlaWdodD0iMTgwIiB2aWV3Qm94PSIwIDAgNzc1IDE4MCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Array expansion](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2ODMiIGhlaWdodD0iMjAyIiB2aWV3Qm94PSIwIDAgNjgzIDIwMiI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Looping through array elements](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3MDIiIGhlaWdodD0iMzE2IiB2aWV3Qm94PSIwIDAgNzAyIDMxNiI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Usage of double quotes with \$@ in for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2ODkiIGhlaWdodD0iMjY3IiB2aWV3Qm94PSIwIDAgNjg5IDI2NyI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Usage of double quotes with \$\* in for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NDUiIGhlaWdodD0iMjAxIiB2aWV3Qm94PSIwIDAgNjQ1IDIwMSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Find leap year with for loop statement](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3NjQiIGhlaWdodD0iNDk0IiB2aWV3Qm94PSIwIDAgNzY0IDQ5NCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Break statement with for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3NzciIGhlaWdodD0iMzcwIiB2aWV3Qm94PSIwIDAgNzc3IDM3MCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Continue statement with for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3ODMiIGhlaWdodD0iMzU5IiB2aWV3Qm94PSIwIDAgNzgzIDM1OSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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. [![Syntax error](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1NzUiIGhlaWdodD0iMTkzIiB2aWV3Qm94PSIwIDAgNTc1IDE5MyI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](https://ostechnix.com/wp-content/uploads/2021/09/Syntax-error.png) Syntax error [![Empty conditional statements](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3NTQiIGhlaWdodD0iMzQ3IiB2aWV3Qm94PSIwIDAgNzU0IDM0NyI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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. [![True keyword](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2MzMiIGhlaWdodD0iMjEyIiB2aWV3Qm94PSIwIDAgNjMzIDIxMiI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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/) ![](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==) ##### [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 [![Ostechnix Footer Logo](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzNDAiIGhlaWdodD0iNjgiIHZpZXdCb3g9IjAgMCAzNDAgNjgiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9IiNjZmQ0ZGIiLz48L3N2Zz4=)](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/). [![OSTechNix](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20250%2052'%3E%3C/svg%3E)](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. [![for loop example](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI5MTIiIGhlaWdodD0iNDIxIiB2aWV3Qm94PSIwIDAgOTEyIDQyMSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![for loop with range](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2OTQiIGhlaWdodD0iMjg3IiB2aWV3Qm94PSIwIDAgNjk0IDI4NyI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Increment values in for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NTYiIGhlaWdodD0iMjUwIiB2aWV3Qm94PSIwIDAgNjU2IDI1MCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Running command in for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI4NDkiIGhlaWdodD0iMjg5IiB2aWV3Qm94PSIwIDAgODQ5IDI4OSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Printing array elements](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3NzUiIGhlaWdodD0iMTgwIiB2aWV3Qm94PSIwIDAgNzc1IDE4MCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Array expansion](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2ODMiIGhlaWdodD0iMjAyIiB2aWV3Qm94PSIwIDAgNjgzIDIwMiI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Looping through array elements](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3MDIiIGhlaWdodD0iMzE2IiB2aWV3Qm94PSIwIDAgNzAyIDMxNiI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Usage of double quotes with \$@ in for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2ODkiIGhlaWdodD0iMjY3IiB2aWV3Qm94PSIwIDAgNjg5IDI2NyI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Usage of double quotes with \$\* in for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NDUiIGhlaWdodD0iMjAxIiB2aWV3Qm94PSIwIDAgNjQ1IDIwMSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Find leap year with for loop statement](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3NjQiIGhlaWdodD0iNDk0IiB2aWV3Qm94PSIwIDAgNzY0IDQ5NCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Break statement with for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3NzciIGhlaWdodD0iMzcwIiB2aWV3Qm94PSIwIDAgNzc3IDM3MCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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 ``` [![Continue statement with for loop](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3ODMiIGhlaWdodD0iMzU5IiB2aWV3Qm94PSIwIDAgNzgzIDM1OSI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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. [![Syntax error](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1NzUiIGhlaWdodD0iMTkzIiB2aWV3Qm94PSIwIDAgNTc1IDE5MyI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](https://ostechnix.com/wp-content/uploads/2021/09/Syntax-error.png) Syntax error [![Empty conditional statements](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3NTQiIGhlaWdodD0iMzQ3IiB2aWV3Qm94PSIwIDAgNzU0IDM0NyI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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. [![True keyword](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2MzMiIGhlaWdodD0iMjEyIiB2aWV3Qm94PSIwIDAgNjMzIDIxMiI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==)](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/)** ![](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0iI2NmZDRkYiIvPjwvc3ZnPg==) ##### [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.
Shard40 (laksa)
Root Hash10538567265436171840
Unparsed URLcom,ostechnix!/bash-for-loop-shell-scripting/ s443