EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Shell Scripting Tutorial For Loop in Shell Scripting
Secondary Sidebar
Shell Scripting Tutorial
  • Shell Scripting Basics
    • What is Shell Scripting
    • Uses of Shell Scripting
    • Shell Scripting Commands
    • Shell Script Parameters
    • Variables in Shell Scripting
    • Shell Script Argument
    • Execute Shell Script
    • Shell Script Set Variable
    • Shell Script Operators
    • Function in Shell Scripting
    • Echo in Shell Scripting
    • if condition in shell script
    • If Statement in Shell Scripting
    • If Else in Shell Scripting
    • Switch Case in Shell Scripting
    • Shell Script Case
    • Loops in Shell Scripting
    • For Loop in Shell Scripting
    • While loop in Shell Scripting
    • Shell Script Set
    • Shell Script Sleep
    • Shell Script Usage
    • Eval in Shell Script
    • Shell Script Read File
    • What is Bash?
    • What is Bash Scripting
    • Bash Shell Script
    • Bash Script Arguments
    • Batch Scripting Commands
    • Bash Script Variables
    • Bash Set Variables
    • Bash Local Variables
    • Bash Variable in String
    • Bash Concatenate Strings
    • Bash Export Variable
    • Bash Alias
    • Bash Trim String
    • Bash Replace String
    • Bash Split String
    • Bash File
    • Shell Scripting Interview Questions
    • Bash String Length
    • Korn Shell Scripting

Related Courses

Shell Scripting Course

Kali Linux Training

Red Hat Training Course

For Loop in Shell Scripting

By Priya PedamkarPriya Pedamkar

For Loop in Shell Scripting

Overview For Loop in Shell Scripting

For loop in Shell Scripting in this, let’s say if we want to perform a task or an operation repetitively we can write the same code those many numbers of times which is a time-consuming task and not efficient too. In order to avoid these types of scenarios, we can use loops like for loop in a programming language. So, for loop is used to perform a particular task like addition/multiplication or any other operation for a certain number of times until the termination condition met in any operating system. We don’t need to write the same code again and again by using for loop.

Syntax of for loop

The syntax of for loop in shell scripting can be represented in different ways as below:

1. First Syntax Method

for var in list
do
command1
command2
done

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,650 ratings)

From the above example, we have pre-defined keywords or built-in keywords such as for, do, done, and in. whereas list is a list of variables or a list of words or a list of numbers and var is a variable name during that iteration. If a list is not provided then bash will take a positional parameter which we passed in the shell. In the above for loop, it will execute all the commands which are there between do and done for n number of times where n is the size of the list. For example, if the size of the list is 5 having numbers from 1 to 5 then during the first iteration 1 will be store in var and operations on var will be performed by the body of the for loop where commands are there.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

2. Second Syntax Method

for ( ( expr1; expr2; expr3 ))
do
command1
command2
….
done

In the above syntax, if we observe this syntax is similar to the syntax of for loop in the c programming language. In for loop, there are three expressions where the first expression is for initialization, second is for conditional check and the third is for updating iterator. The execution in above for loop will start like this, before starting off first iteration expr1 is executed which means initialization will be done after than operations/commands between do and done will be executed iteratively until expr2 evaluates to true and after every iteration expr3 updates the iterator value (counter) so that operations will be performed on next element or value in the list or array or string.

Flow Diagram – For loop in Shell Scripting

Let us consider an example of for loop and discuss the flow of it using the flow diagram.

for filename in *.dat
do
echo cp $fname orig_$fname
done

Flow Diagram - For loop in Shell Scripting

In the above flow diagram, we are explaining the flow of for loop which is iterating over a list of filenames and there are four steps in the flow such as process flow, variable value, process, and stdout. In the process flow, it is explaining when the for loop starts, iterator value, checking the condition if satisfies then runs the process otherwise end the process. In variable value, iteration by iteration we will get a filename in it such as textfile.dat and during the process, it executes echo statement where it displays copy statement with an old filename and new filename on stdout. So, this is the flow of for loop which iterates over the list of input filenames.

Output:

for loop

How for Loop works in Shell Scripting?

For loop in shell script works the following way whenever shell sees the keyword for it knows that it needs to repeat a set of commands once for every item in a list. Each time when iteration runs an item in the list is assigned to the variable var and the var is processed through the list of commands present in the loop between doing and done are executed before moving to the next item in the list or next iteration. We will access the value in the var using $ before the variable so that when shell script processes it the value in the var substitutes in place of it.

Example:

for filename in *.txt
do
ls filename
done

In the above program, we are passing a list of .txt files as input to the for loop and the variable name is a filename in which .txt file will store and then process the filename by listing the .txt file in the filename and then the same process will repeat until all the .txt files processing done.

Output:

for loop

Examples of for loop

So far, we have discussed how for loop works in shell script and different syntaxes. Now, let’s see a few examples and going through them and explain each and every example of what it does

Example #1

Let us a list of static values as input to for loop and how it will execute will see as below:

for a day in Fri Thu Wed Tue Mon
do
echo “Todays day is $day”
done

In the above example, we should not pass input values with, as delimiter if we pass it will consider delimiter is also a value like “Fri,” and we should not list of values using double quotes “if we pass them with double quotes, shell script will treat all values as a single value.

An example o/p: Today day is: Fri Thu Wed Tue Mon ( if we use double quotes)

Output:

for loop in shell scripting

Example #2

Now let us see another example where we use in with for before the input list as below:

Month = “Jan Feb Mar Apr May Jun”
for mon in $Month
do
echo “Month is $mon”
done

In the above example we do the same execution of for loop as above example but instead of input list reading will be done using “in” keyword. In shell scripting, every variable needs to be represented in double-quotes but there are few exceptions such as if we use double quotes in $Month in above for loop line then it will treat entire words as a single line. So we need to take care of it.

Output:

for loop in shell scripting

Example #3

Now, we will write for loop without input list in the for loop statement instead it will take input from positional arguments to the script and example as below:

Let us shell script name as sample.sh and its content as below:

for num
do
echo “Number is $num”
done
./sample.sh 1 2 3 4 5

In the above example, input to for loop is passed from the list of arguments provided to the script so that for each argument it will process all the commands and displays the output until all arguments iterated.

Output:

for loop in shell scripting

Conclusion – For loop in Shell Scripting

Finally, it’s all about for loop in shell scripting. We have discussed what is for loop in shell scripting, for loop syntax, its flow diagram explaining the flow of for loop, how for loop works in shell and examples of for loop in shell scripting. I hope you will have a good understanding of the loop, how to use it in shell scripting and execute it after reading this article.

Recommended Articles

This is a guide to For loop in Shell Scripting. Here we discuss the introduction, How for loop works in shell scripting, Flow Diagram and Example of for loop. You can also go through our other suggested articles to learn more–

  1. Loops in R
  2. Spark SQL Dataframe
  3. Multidimensional Database
  4. Benefits of Data Visualization
  5. Guide to Function in Shell Scripting
  6. Different Examples of Echo in Shell Scripting
  7. What is Bash?
Popular Course in this category
Shell Scripting Training (4 Courses, 1 Project)
  4 Online Courses |  1 Hands-on Project |  18+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Kali Linux Training (3 Courses, 3+ Projects)4.9
Red Hat Linux Training Program (4 Courses, 1+ Projects)4.8
1 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more