while
Shell loop with conditional execution
TLDR
Basic while loop
SYNOPSIS
while CONDITION; do COMMANDS; done
DESCRIPTION
while is a shell control structure that repeatedly executes a block of commands as long as the condition command returns a zero (success) exit status. The loop terminates when the condition returns non-zero.
The condition is typically a test command (or its [ equivalent), but any command can be used. The loop executes as long as the command succeeds.
Common patterns include reading files line by line with read, implementing retry logic, and creating daemon-like processes that run indefinitely.
CONTROL STATEMENTS
break
Exit the loop immediately.break N
Exit N levels of nested loops.continue
Skip remaining commands and start next iteration.continue N
Continue at the Nth enclosing loop.
CAVEATS
Using a pipe to while creates a subshell, so variable changes inside the loop are not visible outside. Use process substitution or here-strings to avoid this: while read line; do ...; done < <(command). Always use read -r to prevent backslash interpretation.
HISTORY
The while loop has been a fundamental shell control structure since the original Bourne shell in Unix Version 7 (1979). The syntax is specified by POSIX and works identically across all POSIX-compliant shells including bash, dash, ksh, and zsh.
