Linux while command (loop – while) [Basic Guide]

The shell has structures for testing conditions and executing certain program sequences several times (loop), until the tested condition is satisfied.

The while command on Linux continuously tests an expression until an expression has a return variable equal to zero or true.

In this example, the variable $i gains an initial value equal to zero.

As long as (while) the test command condition represented by [] returns zero (true), the loop loop will continue to execute.

In the loop, the variable $i is increased until $i reaches the condition of not being less than 4:

$ i=0
$ while [$i -lt 4]; do echo “count $i”; i=$ [$i+1]; done

count 0
count 1
count 2
count 3

The while must have a satisfied exit condition, otherwise it will be in an infinite loop.

If you what to know another form of doing loops in the shell, look the “for” command.

Uirá Endy Ribeiro

Uirá Endy Ribeiro is a Software Developer and Cloud Computing Architect with a 23-year career. He has master's degrees in computer science and fifteen IT certifications and is the author of 11 books recognized in the IT world market. He is also Director at Universidade Salgado de Oliveira and Director of the Linux Professional Institute - LPI Director's Board.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.

Need help?