Categories
Linux

Bash ‘While’ Loop: Tutorial and Examples

Bash (Bourne Again Shell) is a shell command prompt and scripting language in GNU/Linux operating systems. It is the default shell for most Linux distributions.

Like most scripting languages, Bash provides loop syntaxes to repeat similar task multiple times. In this article we will learn how to use the while loop in Bash.

Introduction

The while loop in Bash is used to execute command(s) (executed commands) multiple times based on the output of another command(s) (condition commands). The executed commands will keep running till the condition command runs successfully (i.e., returns a 0 status. Any command in Linux returns 0 for success and a non zero integer for failure).

If there are multiple condition commands, the statement considers only the status of the last command in the list, i.e., the loop executes till the last command in the list runs successfully.

General Syntax

The general syntax for while loop in Bash is:

while <condition_command_list>
do
  <execute_command_list>
done

The execute command list will keep on running till the last command in the condition command list runs successfully and exits with status 0. In the iteration, when the last condition command fails, the loop exits.

User can specify any executable file in the command lists. It can be standard Linux programs or custom user programs or scripts. Each command should be either on a new line or separated by a semicolon on the same line.

Let us see few examples.

Looping till a variable has a particular value: The following loop executes till the value of the variable x is not equal to 10.

x=0
while [[ $x -ne 10 ]]
do
  echo $x
  ((x++))
done

In each iteration, we are checking if the value of x is 10. The value is being checked using the test command. [[ Expression ]] is the syntax for test command (See man test). Here since we are using the -ne operator (which stands for ‘not equal to’), the test command returns 0, i.e. success, if the value of x is not 10, and it returns a non zero value, i.e., failure if the value of x is 10.

Then inside the do...done block, we print the value of x and increment it. Once the value of x is 10, the test command returns non zero status, and the loop exits.

Note: The index variable to be used in while loop is to be initialized either before the while loop or in the condition commands, as opposed to for loop, which enables to initialize a variable implicitly.

With multiple condition commands: The following loop creates 5 directories named dir0, dir1, ... dir4.

z=0
while
echo "List of files:"
ls -l
[[ $z -ne 5 ]]
do
  echo "Creating dir$z..."
  mkdir dir$z
  ((z++))
done

First commands echo "List of files:" and ls -l will execute once completely; their success or failure has no impact whatsoever on how long the loop will run.

Then the test command for checking the value of variable z will execute. Till the value of z is not 5, the test command returns success status, and hence loop keeps on running. The condition commands and executed commands keep running in order. Here, for each iteration, it will first run the echo command and ls command in condition and then 3rd condition command checks for the value of z. If it is not 5, it enters the loop and executes the given commands.

Break and Continue

Break Statement for Conditional Exit

We can also use the conditional statement if inside the loop. The if statement can be used with a break statement, for a conditional exit from the loop.

x=0
while [[ $x -ne 10 ]]
do
  if [[ $x -eq 5 ]]
    break
  fi
  echo $x
  ((x++))
done

The above while loop will print numbers from 0 to 4. Then when the value of i is 5, it will break out of the loop. This is of particular use when a loop is to be exited when a command gives a specific output.

Continue Statement to Skip an Iteration Conditionally

Bash also has a continue statement, to skip remaining part of an iteration in a loop if a particular condition is satisfied.

x=0
while [[ $x -ne 10 ]]
do
  if [[ $x -eq 5 ]]
    continue
  fi
  echo $x
  ((x++))
done

The above loop will print numbers from 0 to 10, except 5, because during the iteration of x=5 there is a continue statement, which will skip rest of the code in the loop at the start with the iteration of x=6.

Using Loops: Scripts and Command Line

The loop syntaxes can be used in Bash shell directly or from an executable shell script file. Similar to for and while loops, once an while loop syntax is entered on the shell, the shell continues the prompt to let the user continue the commands to be looped.

Or else the user can save this in a script file and execute the script file.

The #!/bin/bash at the start specifies the interpreter to be used when the file is executed. Although Bash is the most commonly used shell nowadays, some users do prefer shells like zsh, which should be specified in place of bash at the start of this file.

To give execute permissions for this file, run:

chmod +x test.sh

Finally, to execute the file, run:

./test.sh

Conclusion

The while loop, similar to for and until loops are an important feature in Bash scripting. While loop has a similar use as the until loop, except that it is used to run alternate commands/programs when a particular program succeeds. This often finds its usefulness in advanced networking scripts, system maintenance scripts, etc.