BASH Programming

Syntax for Single Line While Loop in Bash

Bash scripting is used on Unix-based systems for system administration and automating tasks and provides various loop constructs to enable users to repeat a set of commands. One of the loop constructs in bash is the single line while loop. This article will explain the syntax for a single-line while loop in bash and provide a full code example.

What is Syntax for a Single-Line while Loop in Bash

A single-line while loop is mainly used to run a command or a set of commands recursively as far as a specific condition is true so below is the syntax for a single line while loop in bash:

while [ condition ]; do command1; command2; ... ; commandN; done

The condition is evaluated at the beginning of each iteration, and if it is true, the commands inside the loop are executed, whereas the loop will terminate once it becomes false.

#!/bin/bash

echo "Enter any number: "

read number

count=1

while [ $count -le $number ]; do echo $count; ((count++)); done

In this example, the script prompts the user to enter a number, which is stored in the variable num and then a counter variable is initialized with a value of 1. The while loop checks whether the counter is less than or equal to the entered number and if it is, the loop prints the current value of the counter and afterwards increase it by 1.

Conclusion

The single line while loop in bash is quite helpful for executing a set of commands recursively for a certain condition until it is valid. The syntax for the single line while loop is straightforward and easy to understand and this article provided an example of a bash script that uses a single-line while loop to prompt the user for a number and then print out all the numbers up to that number.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.