BASH 06 – While Loops | Linux.org
BASH 06 – While Loops
We previously covered other methods for dealing with logical structures to control the flow of the code. In this article, we will cover another method to repeat code until some value is false.
A While Loop allows the code to loop ‘while’ a value is true. Once the value is false, the loop stops.
While Loop Structure
The structure of the While Loop is like the structures we’ve seen before. The structure is:
while [ test ]; do
command 1
command 2
command n
done
The beginning of the While Loop starts with the reserved word ‘while’. Next is the test that we are checking to loop the code while the test is true. After you state the test, place a semicolon ( and the word ‘do’.
After the ‘while’ line, you can have as many commands as you need. Keep in mind that the commands can consist of ‘if’ statements, any other logic commands, or simple commands. Complete the While Loop with the reserved word ‘done’.
While Loop Example
Let’s look at an example. Copy and paste the code into an editor and save it as ‘numguess.sh’. Perform a ‘chmod 744 numguess.sh’ to make it executable.
#!/bin/bash
num=$(( $RANDOM %10 ))
num=$(( $num + 1 ))
guess=0
while [ $guess -ne $num ]; do
read -p “Select a number between 1 and 10: ” guess
if [ $guess -gt $num ]; then
echo “Too High!”
elif [ $guess -lt $num ]; then
echo “Too Low!”
else
echo “You guessed it!”
fi
done
There are two lines that are completely new that we have not covered. The one uses an actual BASH shell variable. We’ll start after the ‘shebang’.
In this first line of code, we create a random number between 0 and 9. The value after the percent sign (%) signifies the number of possible values, starting with zero. So, by specifying 10, the value range is 0-9. We place the value of the random number into the variable ‘num’.
The second line takes the value of ‘num’ and adds one to it. This makes the new range of ‘num’ between 1 and 10.
The next line creates a new variable and assigns a value of zero to it. We will use the variable ‘guess’ to hold the value that is input by the user. We give it an initial output that is impossible to be a correct guess. By giving it an ‘invalid’ value, we know that when the system enters the While Loop, it cannot match the random number.
The fourth line starts our While Loop. The While Loop is checking that the guess is not equal to the random number. As long as they have not guessed the number, we will continue to let the user guess again until they guess the correct number.
The fifth line allows the user to input a value. We place the guessed value into the variable called ‘guess’ that we already created and set to zero. The variable now has a number, even though we are not verifying that it is a value between 1 and 10.
Now, the sixth line tests the value of the user’s guess to the random number. We test to see if the guess is greater than the random number. If the test is true, we know the guess was too high, and the seventh line echoes the result to the user.
The eighth line is another ‘if’ statement to check if the guess is less than the random number. If the test is true, we notify the user that the guess is too low (line nine).
Line ten is an ‘else’ statement that the guess is neither greater than nor less than. The guess must be equal to the random number. In line 11, the user is told that they guessed the number correctly.
In the twelfth line, the if statement is terminated.
The last line ends the While Loop.
Let’s look at the logic of this script.
Starting up, we generate a random number and we add one to it to get the correct range of 1 to 10. We set the user’s ‘guess’ to an invalid number. The While Loop tests the value and determines that the ‘guess’ value and ‘num’ value are not equal. The flow enters the While Loop.
We prompt the user for a number to be entered, which is placed into the variable ‘num’. We then test the ‘guess’ value to ‘num’ and either inform the user that the guess was too high, too low or correct. If the value is correct, then the While Loop will return a test value of ‘false’ and the Loop is exited. At this point, the script ends.
If the number is too high or low, the ‘guess’ value is still not equal to the ‘num’ variable and the While Loop continues until the guess is correct.
This is a basic script that does not check that the user entered a valid number as requested. Checking the value is something we can look at in a later article, but this can give you the basic idea of how a While Loop works.
We can use the While Loop structure to input from files or even other commands with the Read While Loop.
Read While Loop Structure
Sometimes, you may come across a text file that you need to read and display to the screen in a BASH script.
For instance, a company may use a script to run necessary commands. Before we execute certain commands, a listing of ‘Terms’ needs to be displayed for legal reasons. We can display the contents of the text file.
We can also use the contents of a file for various reasons. We can test each line for its values or content and perform necessary functions on what we read into the script.
Let’s look at the structure of the While Read Loop.
while read <variable>; do
command 1
command 2
command n
done < “$file”
The first line specifies that we want to read from a file from the first line to the last line.
All commands, ‘command1’ to ‘command n’, are to be executed. You can place other structures here as well, such as ‘If’, ‘While Loop’, etc.
The last line specifies that the loop is ‘done’ and gets the file input from the file named ‘$file’. You can place the actual file location and name or use a variable. You can also use the ‘$1’ if you are specifying the filename on the line when you execute the script. For example, if we name the script ‘fileread.sh’ and the text file is ‘file1.txt’ is located in your HOME folder, the command would be ‘./fileread.sh ~/file1.txt’.
While Read Loop Example
Let’s look at an example that I mentioned about displaying a text file for legal reasons. After being displayed, the user must press a key to agree to the terms presented in the displayed information. For ease, let’s say the file is in the ‘/bin’ folder and named ‘Terms.txt’.
while read line; do
echo “$line”
done < “/bin/Terms.txt”
read -n 1 -s -r
We can also process substitution by getting the output from a command. If we would want the output of a command to be processed with the While Read Loop, we can do that. I am keeping it simple by just echoing the content, but you can process the lines looking for specific information and have the script act on it. Let’s say we want to check the contents of the ‘/tmp’ folder. The loop would be:
while read line; do
echo “$line”
done < <(ls /tmp)
We can get the listing and perform any command on the individual files or folders coming back in the list.
Conclusion
The ‘While Loop’ and ‘While Read Loop’ are great commands to create powerful structures in our scripts.
Practice these a bit and you’ll be able to make amazing scripts soon. Not too many items left to go to understanding Bash scripting even better.
Tags:
June 20, 2022 at 01:00AM
Open in Evernote