while

The while loop in Unix-like operating systems is a control structure in shell scripting that repeatedly executes a set of commands as long as a specified condition is true. This can be particularly useful for tasks that need to continue until a particular state is achieved.

Basic Syntax

while condition
do
  commands
done
  • condition: A command or set of commands that return a true (0) or false (non-zero) exit status.

  • commands: The commands to execute as long as the condition is true.

Examples

Basic Example

count=1
while [ $count -le 5 ]
do
  echo "Count: $count"
  count=$((count + 1))
done

Output:

Reading User Input

Checking a Command's Exit Status

Practical Use Cases

Monitoring a Process

Waiting for a File to Exist

Implementing a Simple Menu

Advanced Examples

Infinite Loop with Break Condition

Looping with Multiple Conditions

Conclusion

The while loop is a powerful construct in shell scripting that allows you to execute commands repeatedly based on a condition. It is especially useful for tasks that need to be performed until a certain condition is met or as long as a certain condition remains true. By mastering the while loop, you can write more dynamic and responsive shell scripts.

Last updated