Use of FOR loop in shell script is done when we need to run a command or a set of instructions/commands over & over until a condition has been met. For example, changing the name of some files or changing some information about users on the system etc. Personally, I have used this many times but most recently created a script to automate AMI backup for an AWS account (there are other ways as well but i prefer my bash).
Recommended Read: Bash Scripting-8- Taking user input with READ command in shell script
Syntax for using FOR loop in shell script
for var ( var_name) in list (parameters)
It seems straight forward and simple, now let’s discuss some examples for using for loop in shell script.
for name in Dan Susan Daniel
echo “Welcome $name”
So the name of the variable is ‘name’ & list of parameters is ‘dan susan daniel’. So the output of the following script would be,
We can also modify the script to read from a variable or use the output of a command as a list. Let’s see an example,
name=”Dan Susan Daniel”
for member in $name
echo “Welcome again $member”
Now the output would be,
We can also create a file with a list & instead of writing a list inside a script, we can just mention the path of the file that has the list. Let’s see an example,
for member in $(cat $file)
echo “Welcome $member ”
/home/ec2-user/list.txt is the list & we enter names or other information either one per line, or using a single space or a tab between info. But we can’t use commas to separate them, caused by default space, tab & newlines are interpreted as separators.
Another thing that I would like to discuss is the use of escape character while using for loop in shell script. While using words like can’t, don’t, won’t, we either need to use double quotations “” or escape symbol \ in, like
“Won’t” don\’t “can’t”
Using C language style for loop in shell script
Above mentioned way is not the only method that we use for loop in shell script. We can also use the for loop C language style. Let’s see the syntax,
for ((i=0; i=10; i++))
So here, we mentioned to start loop at 0 & it can go upto 10 with an increment of one. So let’s say we need to check about system ram continuously for 10 minutes, every sixty second, then we can use this C style for loop to achieve this,
for ((i=0; i=600; i=i+10))
echo “RAM stats are”
Now let’s check another example where we are also utilizing other conditional statements,
for file in /home/ec2-user/*
if [ -d “$file”]
echo”$file is a directory”
elif [ -f “$file”]
echo “$file is a file not a directory”
So this is it for using for loop in shell script. Please feel free to send in any request, suggestion, or questions using the comment box below.