While Statement

Learn about the while operator in detail.

while

Bash provides two loop operators: while and for. We will start with the **while** statement because it is more straightforward than for.

The while syntax resembles the if statement. If we write while in the general form, it looks like this:

while CONDITION
do
  ACTION
done

We can write the while statement in one line:

while CONDITION; do ACTION; done

Both CONDITION and ACTION can be a single command or block of commands. The ACTION is called the loop body.

When Bash executes the while loop, it checks the CONDITION first. If a command of the CONDITION returns the zero exit status, it means “true.” Bash executes the ACTION in the loop body in this case. Then, it rechecks the CONDITION. If it still equals “true,” the ACTION is performed again. The loop execution stops when the CONDITION becomes “false.”

Let’s use the while loop when we do not know the number of iterations beforehand. A good example of this case is busy waiting for some event.

Let’s suppose that we write a script that checks if some web server is available. The simplest check looks like this:

  1. Send a request to the server.

  2. Receive the response.

  3. If there is no response, the server is unavailable.

When the script receives the response from the server, it should print a message and stop.

We can call the ping utility to send a request to the server. The utility uses the ICMP protocol.

A protocol is an agreement for the format of messages between the computers of the network. The ICMP protocol describes the messages to serve the network. For example, we need them to check if some computer is available.

When calling the ping utility, we should specify an IP address or URL of the target host. A host is a computer or device connected to the network.

Here is an example of the ping call:

ping google.com

Run the commands discussed in this lesson in the terminal below.

Get hands-on with 1400+ tech skills courses.