Looping 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
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.