Shell Scripting With Bash (Part-2)
Loops:
Most of the time, few tasks needs to be executed repeatedly either a fixed number of times or until a specified condition is satisfied. That is where the looping constructs comes into the picture. In Bash scripting, there are three major loops, “for loop”, “while loop” and “until loop”.
FOR Loop:
Similar to other programming languages, bash also provides the ‘for’ loop. The syntax is same and one more advantage we have here is that, we can run loop by providing/reading the file as list. For loop construct is used to operate on each element of a list. We can specify list explicitly by listing each item one by one or as the result of a particular command (e.g cat somefile).
The basic syntax of the for loop is:
for VARIABLE in list
do
Run command on $VARIABLE
done
VARIABLE holds the value of item in list during each iteration.
For example, we can create ‘n’ number of files by appending the file name with number as:
for n in 1 2 3 4 5
do
touch file$n.txt
done
In above example, the for loop will run five time and in each iteration, ‘n’ will hold the one value from list ( 1 to 5) and output will be file1.txt, file2.txt, file3.txt, file4.txt, file5.txt respectively.
We can also provide the output of command as list to be used in for loop.
For example, we will use “ls” command with “grep” to filter only files with name start with “file” (we have just created above) and we will change the permission to 755 for each file.
for F in $(ls -l | grep file)
do
chmod 755 $F
done
The result would be changed files permissions.
While Loop:
It is opposite to the “for loop”, where we don’t know the number of iterations to run the loop for. ‘while loop’ is typically used when the number of iterations is not known beforehand or when using for is impractical.
Let’s take an example of reading a file line by line, by increasing or decreasing the value of a variable until it reaches a given value, or responding to user input.
Syntax for “while loop”:
while condition is true
do
Run commands here
done
To illustrate, let's consider an examples. Let's create a simple file with some lines into it.
I will create a file called Fruites.txt and will put data as:
Apple
Banana
Mango
Pineapple
Orange
We will read this file line by line and return a message showing each line. This is an example of the case when we need to repeat iteration for undetermined number of times.
while read LINE
do
echo "$LINE is from Fruites.txt file"
done < Fruites.txt
In this example, we are checking at the beginning of each iteration is whether we have reached the end of the file. The variable named “LINE” represents each line in Fruites.txt. This file is set as the input to the loop by using the < redirection operator.
Let's take a look at the output of the while loop:
Apple is from Fruites.txt file
Banana is from Fruites.txt file
Mango is from Fruites.txt file
Pineapple is from Fruites.txt file
Orange is from Fruites.txt file
I fund the below script on internet which is very interesting and very good example of while loop:
We will write a simple number-guessing game in a script called guess.sh. When the script is launched, a random number between 1 and 10 is generated and stored in the variable RANDOMNUM. The script then will expect input from the user and indicate if the guess is correct, less than, or greater than the right number. This will continue until the user guesses the number correctly. In this example, $NUMBER != $RANDOMNUM is enclosed within square brackets to indicate accurately what is the condition to test.
#!/bin/bash
RANDOMNUM=$(shuf -i1-10 -n1)
NUMBER=0
while [ $NUMBER != $RANDOMNUM ]
do
read -p "Enter a number between 1 and 10: " NUMBER
done
echo "Congratulations! Your guess was right!"
Just copy and paste the above script and do let me know your out put in comment section.
Until loop:
The “until loop” is used to execute a given set of commands as long as the given condition evaluates to false. That means, the loop will continue until the condition gets true.
Syntax for Until Loop:
until [CONDITION]
do
[COMMANDS]
done
Here before executing the commands the condition is get evaluated. If it is false, commands are executed. Otherwise, the loop will be terminated and the program control will be passed to the command that follows.
In below example, on each iteration the loop prints the current value of the variable counter and variable value gets increased by one.
count=0
until [ $count -gt 3 ]
do
echo Count for: $count
((count++))
done
This loop will run until the “count” value is greater than 2.
OutPut:
Count for: 0
Count for: 1
Count for: 2
Count for: 3
Let’s take another example, here I have written a simple script for checking particular IP, I will say this is my server IP and I want to check connectivity whenever there is downtime, I use to do ping to that server, but I don’t know when will the server will be up and running.So I would have to ping manually for n number of time.
So, below code will check the server connectivity until it comes up.
until ping -c2 192.168.0.1 &> /dev/null
do
echo "Waiting for the host ..."
sleep 1
done
echo -e "\nThe server is up and running now."
Whenever there is down time, I will run the script and set back.
The expected output will be:
user@server:~$ ./scriptUntil.sh
Waiting for the host ...
Waiting for the host ...
Waiting for the host ...
Waiting for the host ...
The server is up and running now.
If I run for second time while server is already running:
user@server:~$ ./scriptUntil.sh
The server is up and running now.
Useful links: