How to write Bash WHILE-Loops

You can run a script by writing it to a script file and then running it.

A script file is simply a text file, usually with the .SH file extension, containing a sequence of instructions that could also be executed from the command line (shell).

While-Loop Examples

Below is an example of a time loop. When run, this script file will print the numbers 1 through 9 to the screen. The while statement gives you more flexibility in specifying the termination condition than does the for-loop.

For example, you can make the above script an infinite loop by omitting the “((count+++)]” increment statement:

The “sleep 1” statement stops execution for 1 second on each iteration. Use the keyboard shortcut Ctrl+C to finish the process.

You can also create an infinite loop by putting a colon as a condition:

To use multiple conditions in the time loop, you must use the double bracket notation:

In this script, the variable “done” is initialized to 0 and then set to 1 when the count reaches 5. The loop condition says that the loop will continue as long as “count” is less than nine and “done” is equal to zero. Therefore, the loops exit when the count equals 5.

“&&” means logical “and” and “||” means logical ‘or’.

An alternative notation for the conjunctions “and” and “or” in conditions is “-a” and “-o” with single square brackets. The above condition:

…could be rewritten as:

Reading from a text file is normally done with a time loop. In the following example, the bash script reads the content line by line from a file called “inventory.txt:”

The first line assigns the name of the input file to the variable “FILE”. The second line stores the “standard input” in file descriptor “6” (can be any value between 3 and 9). This is done so that the “standard input” can be restored to file descriptor “0” at the end of the script (see “exec 0” statement) In the third line the input file is assigned to file descriptor “0” , which is used for standard input.The “read” statement then reads one line from the file at each iteration and assigns it to the variable “line1”.

To prematurely exit a time loop, you can use the break statement like this:

The break statement skips the execution of the program to the end of the loop and executes any statement that follows it. In this case, the phrase “echo Finished”.

The continue statement, on the other hand, skips just the rest of the while loop statement for the current iteration and jumps directly to the next iteration:

In this case, the “continue” statement is executed when the “count” variable reaches 5. This means that the next statement (echo “$count”) is not executed in this iteration (when the value of “count” is 5) .

TechnoAdmin