Cyberithub

How to decide the Usage of for loop and while loop in Shell Scripting

Advertisements

In this article, we will see how to decide the usage of for and while loop in Shell scripting. It was not very long ago when I started working on some shell scripts to automate some of my manual tasks where I had to regularly use for and while loop to run through series of inputs. But I was so utterly confused between the usage of for and while loop, as a result I always ended up using them in wrong places.

I am sure lot many people who started using Bash or shell scripting might face this problem as well especially all those folks who is not from any scripting or programming background. So I thought to write an article about this to explain the usage of for and while loop clearly to give you a better understanding about its place of usage.

 

How to decide the Usage of for loop and while loop in Shell Scripting

How to decide the Usage of for loop and while loop in Shell Scripting

Also Read: Solved "syntax error: unexpected end of File" in Linux Shell Scripting

If you are doing Shell scripting then you probably know there are majorly four types of loops in bash shell scripting - for loop, while loop, until loop and select loop in which for loop and while loop are most frequently and widely used. While the usage of both for and while loop are entirely dependent on how a scripting professional would like to use it in their case but in general it is decided by the input you need to provide.

For example, if you would like to provide a series of lines or rows as an input and expecting to take an entire line or row as an input one by one which includes strings separated by spaces or by any other delimiters then using while loop here would be a much better idea than using a for loop.

It is simply because for loop will split the entire row into multiple strings based on delimiters present between the strings. It will only take one string from the entire row at a time as an input instead of taking entire row. Then in next iteration it will take next string from the same row and so on until the end of the row.

But this won't be the case with while loop. It will take entire line or row as an input and then you can perform certain operation on that under do..done block. This can be further understood by an illustration. Here we will see a simple example script where we will get the status of kubernetes cluster pods and will go through each row of the output to check the pod running status. We will use both for loop and while loop to go through each line or row of kubectl get pods output and see how both loops treat input differently.

 

Kubernetes Cluster

Context: pr-hcm-u01

[cyberithub@node1 ~]$ kubectl get pods
NAME                          READY  STATUS   RESTARTS AGE
app-hcm-66b6c48dd5-bzqj6      1/1    Running  0        15m
consumer-app-66b6c48dd5-dw567 1/1    Pending  0        15m
product-app-66b6c48dd5-wfvf2  1/1    Running  0        15m

 

1) For Loop

#!/bin/bash 

for i in $(kubectl config use-context pr-hcm-u01 | grep -v Switched;kubectl get pods | grep -v STATUS)
do
  echo $i > pods.txt 
  if [ "$(awk '{print $3}' pods.txt)" != "Running" ];then
     echo "$(awk '{print $1}' pods.txt) is not running"
  else 
     true
  fi
done
rm pods.txt

 

Output

[cyberithub@node1 ~]$ ./checkPods.sh 
app-hcm-66b6c48dd5-bzqj6 is not running
1/1 is not running
Running is not running
0 is not running
15m is not running
consumer-app-66b6c48dd5-dw567 is not running
1/1 is not running
Pending is not running
0 is not running
15m is not running
product-app-66b6c48dd5-wfvf2 is not running
1/1 is not running
Running is not running
0 is not running
15m is not running

 

Explanation
As you can see from the above output, for loop took one string at a time from a specific row and checked it for if condition instead of taking entire row as input. Hence in this type of scenario where you have a row with multiple strings separated by delimiters, it would not be appropriate to use for loop here as it will split the input.

 

2) While Loop

#!/bin/bash

kubectl config use-context pr-hcm-u01 | grep -v Switched;kubectl get pods | grep -v STATUS | while read data
do 
  echo $data > pods.txt 
  if [ "$(awk '{print $3}' pods.txt)" != "Running" ];then 
     echo "$(awk '{print $1}' pods.txt) is not running" 
  else 
     true 
  fi 
done
rm pods.txt

 

Output

[cyberithub@node1 ~]$ ./checkPods.sh 
consumer-app-66b6c48dd5-dw567 is not running

 

Explanation
As you can see from the above output, while loop treated the entire line or row as an input and given it to awk command to query column 1 and column 3 from it. As a result, it is successfully able to verify the validity of if condition by checking the pods status from column 3 and shown the pod with pending status on the output. So here while loop would be most appropriate to use.

Leave a Comment