Skip to main content
Bash ScriptingCentOS

WHILE loops in BASH

By April 15, 2013September 12th, 2022No Comments

while loopsLooping in any scripting environment will be useful and fun, helping us with those repetitive tasks that we hate. There are many forms of loops and in this tutorial, we take our first look at look at WHILE loops. Using while loops in bash we will continue to loop whilst a condition is true. Looping means that we will keep running the code located in the do and done block. To help us understand while loops we start with some initial pseudo-code. Take a look at the following example:

while test-expression
do
  command-list
done
 Working with something just a little more real we can view the following example. The script is simple and refers to a counter reaching the desired value. In our case, we start the counter with a value of then and loop until it reaches zero. We could implement something similar to limit a login process to three attempts. The times that we can a process like this is endless.
COUNT=10
while (( COUNT > 0 ))
do
  echo -e "$COUNT \c"
  sleep 1
  (( COUNT -- ))
done
echo -e "\n\nFIRE!!"
 You will notice in the code that we use the echo command with the -e option. This allows us to embed escape sequences into the text. We first use \c to suppress the line feed followed by the \n where we need additional line-feeds.

The counter starts at 10 and in each cycle of the loop is reduced by one. This is achieved with the code: (( COUNT — )). When the counter is no longer greater than 0 we exit the loop and print the word FIRE.
We could also look at adding a while loop to provide the basics of a menu system. In lesson 4 we looked at the script that could list files, directories or links. Rather than run the script many times we can keep the script running awaiting your new input and list all items.