Bash Script for Loop Explained with Examples | phoenixNAP KB (2022)

Introduction

The for loop is an essential programming functionality that goes through a list of elements. For each of those elements, the for loop performs a set of commands. The command helps repeat processes until a terminating condition.

Whether you're going through an array of numbers or renaming files, for loops in Bash scripts provide a convenient way to list items automatically.

This tutorial shows how to use Bash for loops in scripts.

Bash Script for Loop Explained with Examples | phoenixNAP KB (1)

Prerequisites

  • Access to the terminal/command line (CTRL+ALT+T).
  • A text editor, such as Nano or Vi/Vim.
  • Elementary programming terminology.

Bash Script for Loop

Use the for loop to iterate through a list of items to perform the instructed commands.

The basic syntax for the for loop in Bash scripts is:

for <element> in <list>do<commands>done

The element, list, and commands parsed through the loop vary depending on the use case.

Bash For Loop Examples

Below are various examples of the for loop in Bash scripts. Create a script, add the code, and run the Bash scripts from the terminal to see the results.

Individual Items

Iterate through a series of given elements and print each with the following syntax:

#!/bin/bash# For loop with individual numbersfor i in 0 1 2 3 4 5do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (2)

Run the script to see the output:

. <script name>
Bash Script for Loop Explained with Examples | phoenixNAP KB (3)

The script prints each element from the provided list to the console.

Alternatively, use strings in a space separated list:

#!/bin/bash# For loop with individual stringsfor i in "zero" "one" "two" "three" "four" "five"do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (4)

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

Bash Script for Loop Explained with Examples | phoenixNAP KB (5)

The output prints each element to the console and exits the loop.

Range

Instead of writing a list of individual elements, use the range syntax and indicate the first and last element:

#!/bin/bash# For loop with number rangefor i in {0..5}do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (6)

The script outputs all elements from the provided range.

Bash Script for Loop Explained with Examples | phoenixNAP KB (7)
(Video) Beyond Code Live 009 Practical Bash: Variables and For Loops in Scripts

The range syntax also works for letters. For example:

#!/bin/bash# For loop with letter rangefor i in {a..f}do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (8)

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

Bash Script for Loop Explained with Examples | phoenixNAP KB (9)

The range syntax works for elements in descending order if the starting element is greater than the ending.

For example:

#!/bin/bash# For loop with reverse number rangefor i in {5..0}do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (10)

The output lists the numbers in reverse order.

Bash Script for Loop Explained with Examples | phoenixNAP KB (11)

The range syntax works whether elements increase or decrease.

Range with Increment

Use the range syntax and add the step value to go through the range in intervals.

For example, use the following code to list even numbers:

#!/bin/bash# For loop with range increment numbersfor i in {0..10..2}do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (12)

The output prints every other digit from the given range.

Bash Script for Loop Explained with Examples | phoenixNAP KB (13)

Alternatively, loop from ten to zero counting down by even numbers:

#!/bin/bash# For loop with reverse range increment numbersfor i in {10..0..2}do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (14)

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

Bash Script for Loop Explained with Examples | phoenixNAP KB (15)

Exchange increment 2 for any number less than the distance between the range to get values for different intervals.

The seq Command

The seq command generates a number sequence. Parse the sequence in the Bash script for loop as a command to generate a list.

For example:

#!/bin/bash# For loop with seq commandfor i in $(seq 0 2 10)do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (16)

The output prints each element generated by the seq command.

(Video) Beyond Code Live 009 Practical Bash: Variables and For Loops in Scripts

The seq command is a historical command and not a recommended way to generate a sequence. The curly braces built-in methods are preferable and faster.

C-Style

Bash scripts allow C-style three parameter for loop control expressions. Add the expression between double parentheses as follows:

#!/bin/bash# For loop C-stylefor (( i=0; i<=5; i++ ))do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (17)

The expression consists of:

  • The initializer (i=0) determines the number where the loop starts counting.
  • Stop condition (i<=5) indicates when the loop exits.
  • Step (i++) increments the value of i until the stop condition.

Separate each condition with a semicolon (;). Adjust the three values as needed for your use case.

The terminal outputs each element, starting with the initializer value.

Bash Script for Loop Explained with Examples | phoenixNAP KB (18)

The value increases by the step amount, up to the stop condition.

Infinite Loops

Infinite for loops do not have a condition set to terminate the loop. The program runs endlessly because the end condition does not exist or never fulfills.

To generate an infinite for loop, add the following code to a Bash script:

#!/bin/bash# Infinite for loopfor (( ; ; ))do echo "CTRL+C to exit"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (19)

To terminate the script execution, press CTRL+C.

Bash Script for Loop Explained with Examples | phoenixNAP KB (20)

Infinite loops are helpful when a program runs until a particular condition fulfills.

Break

The break statement ends the current loop and helps exit the for loop early. This behavior allows exiting the loop before meeting a stated condition.

To demonstrate, add the following code to a Bash script:

#!/bin/bash# Infinite for loop with breaki=0for (( ; ; ))do echo "Iteration: ${i}" (( i++ )) if [[ i -gt 10 ]] then break; fidoneecho "Done!"
Bash Script for Loop Explained with Examples | phoenixNAP KB (21)

The example shows how to exit an infinite for loop using a break. The Bash if statement helps check the value for each integer and provides the break condition. This terminates the script when an integer reaches the value ten.

Bash Script for Loop Explained with Examples | phoenixNAP KB (22)

To exit a nested loop and an outer loop, use break 2.

Continue

The continue command ends the current loop iteration. The program continues the loop, starting with the following iteration. To illustrate, add the following code to a Bash script to see how the continue statement works in a for loop:

#!/bin/bash# For loop with continue statementfor i in {1..100}do if [[ $i%11 -ne 0 ]] then continue fi echo $idone
Bash Script for Loop Explained with Examples | phoenixNAP KB (23)

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

Bash Script for Loop Explained with Examples | phoenixNAP KB (24)
(Video) "seq" command tutorial - Create 100s & 1000s of empty files

The conditional if statement checks for divisibility, while the continue statement skips any numbers which have a remainder when divided by eleven.

Arrays

Arrays store a list of elements. The for loop provides a method to go through arrays by element.

For example, define an array and loop through the elements with:

#!/bin/bash# For loop with arrayarray=(1 2 3 4 5)for i in ${array[@]}do echo "Element $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (25)

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

Bash Script for Loop Explained with Examples | phoenixNAP KB (26)

The Bash for loop is the only method to iterate through individual array elements.

Indices

When working with arrays, each element has an index.

List through an array's indices with the following code:

#!/bin/bash# For loop with array indicesarray=(1 2 3 4 5)for i in ${!array[@]}do echo "Array indices $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (27)

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

Bash Script for Loop Explained with Examples | phoenixNAP KB (28)

The output prints numbers from zero to four for an array with five elements.

Nested Loops

To loop through or generate multi-dimensional arrays, use nested for loops.

As an example, generate decimal values from zero to three using nested loops:

#!/bin/bash# Nested for loopfor (( i = 0; i <= 2; i++ ))do for (( j = 0 ; j <= 9; j++ )) do echo -n " $i.$j " done echo "" done
Bash Script for Loop Explained with Examples | phoenixNAP KB (29)

The code does the following:

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

The output prints each number combination to the console and enters a new line when the outer loop finishes one iteration.

Strings

To loop through words in a string, store the string in a variable. Then, parse the variable to a for loop as a list.

For example:

#!/bin/bash# For loop with stringstrings="I am a string"for i in ${strings}do echo "String $i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (31)

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

Bash Script for Loop Explained with Examples | phoenixNAP KB (32)
(Video) 019 - Shell Scripting #01 | Introduction To Shell Scripting | Working With Arguments And Variables

The output prints individual words from the string to the console.

Files

The for loop combined with proximity searches helps list or alter files that meet a specific condition.

For example, list all Bash scripts in the current directory with a for loop:

#!/bin/bash# For loop with filesfor f in *.shdo echo $fdone
Bash Script for Loop Explained with Examples | phoenixNAP KB (33)

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

Bash Script for Loop Explained with Examples | phoenixNAP KB (34)

Loop through files or directories to automatically rename or change permissions for multiple elements at once.

Command Substitution

The for loop accepts command substitution as a list of elements to iterate through.

The next example demonstrates how to write a for loop with command substitution:

#!/bin/bash# For loop with command substitutionlist=`cat list.txt`# Alternatively, use list=$(cat list.txt)for i in $listdo echo $idone
Bash Script for Loop Explained with Examples | phoenixNAP KB (35)

The Bash comment offers an alternative syntax for command substitution. The code reads the contents of the list.txt file using the cat command and saves the information to a variable list.

Bash Script for Loop Explained with Examples | phoenixNAP KB (36)

Use the command substitution method to rename files from a list of names saved in a text file.

Note: Learn how to use the cat command and for loop to read files line by line in Bash.

Command Line Arguments

Use the for loop to iterate through command line arguments.

The following example code demonstrates how to read command line arguments in a for loop:

#!/bin/bash# For loop expecting command line argumentsfor i in [emailprotected]do echo "$i"done
Bash Script for Loop Explained with Examples | phoenixNAP KB (37)

Provide the command line arguments when you run the Bash script.

For example:

. <script name> foo bar
Bash Script for Loop Explained with Examples | phoenixNAP KB (38)

The [emailprotected] substitutes each command line argument into the for loop.

Conclusion

(Video) Bash Scripts Examples

After following this tutorial, you know how to use the for loop in Bash scripts to iterate through lists.

Next, learn how to write and use Bash functions.

FAQs

How does a bash for loop work? ›

A bash for loop is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script. For example, you can run UNIX command or task 5 times or read and process list of files using a for loop.

What is $1 and $2 in shell script? ›

$0 is the name of the script itself (script.sh) $1 is the first argument (filename1) $2 is the second argument (dir1)

How do you put a loop in a bash script? ›

We can apply 'for loop' on bash script in two ways. One way is 'for-in' and another way is the c-style syntax. Following is the syntax of 'for loop' in bash shell scripting: for variable in list.

What are the three types of loops in bash scripting? ›

In scripting languages such as Bash, loops are useful for automating repetitive tasks. There are three basic loop constructs in Bash scripting, for loop, while loop , and until loop . In this tutorial, we will cover the basics of for loops in Bash.

What is for loop with syntax and example? ›

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.

What is $? $# $*? ›

$# Stores the number of command-line arguments that were passed to the shell program. $? Stores the exit value of the last command that was executed. $0 Stores the first word of the entered command (the name of the shell program). $* Stores all the arguments that were entered on the command line ($1 $2 ...).

What is $? == 0 in shell script? ›

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What does [- Z $1 mean in bash? ›

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

What is the syntax of for loop? ›

Example explained

Statement 1 sets a variable before the loop starts (int i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.

What are the 3 expressions in a for loop? ›

Each for-loop consists of three parts: init: This statement (usually) defines the loop control variable in loop-scope and initializes it: int i = 0; .
...
update: this statement updates the loop control variable in such a way that the test will eventually become false:
  • i++
  • i += 2.
  • i--
  • i -= 2.
  • i = (int)pow(2, i+2)

What are 4 key components in a loop? ›

Answer: Loop statements usually have four components: initialization (usually of a loop control variable), continuation test on whether to do another iteration, an update step, and a loop body.

What are 2 types of loops? ›

There are two types of loops, “while loops” and “for loops”. While loops will repeat while a condition is true, and for loops will repeat a certain number of times. You'll also learn about for each loops which are a type of for loop that repeats once for each item in a list.

What are the three main types of loop with example? ›

In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java executes a set of repeated statements as long as a specified condition remains true. This particular condition is generally known as loop control.

What are the 5 types of loops? ›

  • Types of Loops.
  • While Loop.
  • Do-While loop.
  • For loop.
  • Nested loop.
  • Break Statement.
  • Continue Statement.
13 Aug 2020

What is the formula for a loop? ›

Kirchhoff's rules

The second rule, the loop equation, states that around each loop in an electric circuit the sum of the emf's (electromotive forces, or voltages, of energy sources such as batteries and generators) is equal to the sum of the potential drops, or voltages across each of the resistances, in…

How do you start writing a for loop? ›

It starts with the for keyword, followed by a value name that we assign to the item of the sequence ( country in this case). Then, the in keyword is followed by the name of the sequence that we want to iterate. The initializer section ends with “ : ”.

What does GTF mean in texting? ›

Gone too far. When someone says you've GTF (gone too far), it means you did or said something incredibly distasteful. For example, someone may tell you you've GTF after you key their car or send them a crude joke. Typically, when someone says you've GTF, it's polite to apologize for whatever unpleasant thing you did.

What does Div stand for *? ›

DIV
AcronymDefinition
DIVDivision
DIVDivide (street type)
DIVDiving
DIVDivider
13 more rows

What called in this symbol *? ›

Asterisk

What is $() called in Bash? ›

It turns out, $() is called a command substitution. The command in between $() or backticks (“) is run and the output replaces $() . It can also be described as executing a command inside of another command.

What is $$ in shell script? ›

$$ The process number of the current shell. For shell scripts, this is the process ID under which they are executing.

What is $? In Linux? ›

The return value of a command is stored in the $? variable. cmd; echo $?; The return value is called exit status. This value can be used to determine whether a command completed successfully or unsuccessfully.

What does if [- Z mean in shell? ›

The -z flag causes test to check whether a string is empty. Returns true if the string is empty, false if it contains something. NOTE: The -z flag doesn't directly have anything to do with the "if" statement. The if statement is used to check the value returned by test. The -z flag is part of the "test" command.

What does $_ mean in bash? ›

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

What does == mean in bash? ›

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison. eq being a numeric comparison of course.

What is for loop in shell script? ›

The for loop operate on lists of items. It repeats a set of commands for every item in a list. Here var is the name of a variable and word1 to wordN are sequences of characters separated by spaces (words).

How does a for loop work? ›

In for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than the counter value. If the statement is true, then the loop body is executed and the loop variable gets updated.

What is i ++ in for loop? ›

The difference is that the post-increment operator i++ returns i as it was before incrementing, and the pre-increment operator ++i returns i as it is after incrementing. If you're asking about a typical for loop: for (i = 0; i < 10; i++) or for (i = 0; i < 10; ++i)

Why bash script is used? ›

Bash scripting allows a user to elegantly sequence commands together, as well as review commands to avoid potential havoc on data, files, and file structures. Style conventions in your scripts help the debugging process and enable fellow programmers to more easily read the code.

What is the format of a bash script? ›

A basic Bash script has three sections. Bash has no way to delineate sections, but the boundaries between the sections are implicit. All scripts must begin with the shebang (#!), and this must be the first line in any Bash program. The functions section must begin after the shebang and before the body of the program.

What are bash commands? ›

Bash is a command processor that typically runs in a text window where the user types commands that cause actions. Bash can also read and execute commands from a file, called a shell script.

What does [- Z $1 mean in bash? ›

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

How does for loop work in Linux? ›

The basic syntax of a for loop is: for <variable name> in <a list of items>;do <some command> $<variable name>;done; The variable name will be the variable you specify in the do section and will contain the item in the loop that you're on.

Is it true 1 or 0 bash? ›

There are no Booleans in Bash. However, we can define the shell variable having value as 0 (“ False “) or 1 (“ True “) as per our needs.

What does $() mean in bash? ›

Example of command substitution using $() in Linux:

Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).

What is $? $# $*? ›

$# Stores the number of command-line arguments that were passed to the shell program. $? Stores the exit value of the last command that was executed. $0 Stores the first word of the entered command (the name of the shell program). $* Stores all the arguments that were entered on the command line ($1 $2 ...).

What is $? == 0 in shell script? ›

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What does if [- Z mean in shell? ›

The -z flag causes test to check whether a string is empty. Returns true if the string is empty, false if it contains something. NOTE: The -z flag doesn't directly have anything to do with the "if" statement. The if statement is used to check the value returned by test. The -z flag is part of the "test" command.

What are the 5 types of loops? ›

  • Types of Loops.
  • While Loop.
  • Do-While loop.
  • For loop.
  • Nested loop.
  • Break Statement.
  • Continue Statement.
13 Aug 2020

What are the 3 main parts of a for loop? ›

The For-EndFor Statement Structure

Similar to a While loop, a For loop consists of three parts: the keyword For that starts the loop, the condition being tested, and the EndFor keyword that terminates the loop. JAWS performs all statements found in the boundaries of the loop as long as the loop condition is true.

Why is it called a for loop? ›

For loops will repeat a block of code a set number of times. The reason they are called for loops is that you can tell your app how many times you want it to repeat to the code for. You can think about for loops as telling your app, “repeat this, for 17 times” or “repeat this, for 5 times”.

Why do hackers use bash? ›

Because Bash can be used with other networks, hacking tools, and programming languages to deliver the payload to the target, it helps exfilleting the data from the victim and create a remote executable application.

What does $1 mean in Bash script? ›

$1 is the first commandline argument. If you run ./asdf.sh a b c d e, then $1 will be a, $2 will be b, etc. In shells with functions, $1 may serve as the first function parameter, and so forth. $1, beginners.

Is bash difficult to learn? ›

Overall, Bash is relatively easy to learn. Most students can learn basic, intermediate, and advanced commands within six months.

What is $_ in bash? ›

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

What means && in bash? ›

"&&" is used to chain commands together, such that the next command is run if and only if the preceding command exited without errors (or, more accurately, exits with a return code of 0). "\" by itself at the end of a line is a means of concatenating lines together.

What does += mean in bash? ›

The += and -= Operators

These operators are used to increment/decrement the value of the left operand with the value specified after the operator. ((i+=1)) let "i+=1" ((i-=1)) let "i-=1"

Videos

1. Passing The Arguments in Shell Script | Bash Shell Scripting Tutorial For Beginners | Session-4
(Nehra Classes)
2. CosmoStat Tutorial: Bash and Scripting Tutorial for Researchers
(CosmoStat)
3. Shell Script to find the reverse of the string
(Irshad Rahimy)
4. EE798B class bash scripts
(MADHAVlab IITK)
5. Introduction to Bash
(Microsoft Reactor)
6. Shell Scripting Tutorial | Shell Scripting Crash Course | Linux Certification Training | Edureka
(edureka!)

Top Articles

Latest Posts

Article information

Author: Laurine Ryan

Last Updated: 10/05/2022

Views: 5589

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.