while loop
A loop that keeps repeating its block as long as a condition stays true, checking the condition before each pass.
In more detail
Use while when you cannot know in advance how many passes are needed, such as reading input until the user types nothing. Something in the body must eventually make the condition false, or the loop never stops. When the number of passes is known, a for loop is simpler.
Examples
while [[ $count -le 3 ]]; do ((count++)); donetemperature = 115
while temperature > 112:
temperature = temperature - 1Related terms
- until loop — A loop that runs its body again and again until a test command succeeds, the reverse of while.
- for loop — A loop that runs its body once for each item in a list or other collection, setting a loop variable to the current item.
- read builtin — The bash builtin that reads one line of input and stores it, or its fields, in variables.
- break and continue — Builtins that change a loop's flow: break leaves the loop at once and continue skips to the next turn.
- infinite loop — A loop or cycle that never stops, because the condition that should end it is never reached.
- sentinel — A special value that cannot occur in the real data and signals the end of it, such as an empty line ending a list of entries.
- condition — An expression that is tested for being true or false, such as weight > 50, to decide what a program does next.
Taught in
- The Field Separator, And Reading Lines Safely — Bash Scripting & Command Line Automation
- Command Substitution And Subshells — Bash Scripting & Command Line Automation
- Loops: for, while, until, break, continue — Bash Scripting & Command Line Automation
- Script Input And Output: read, Heredocs, printf — Bash Scripting & Command Line Automation
- Functions, local And declare — Bash Scripting & Command Line Automation
- Arguments: Dollar One, Dollar At, shift — Bash Scripting & Command Line Automation
- Option Parsing With getopts — Bash Scripting & Command Line Automation
- Lists, Range And The For Loop — Hands-on Python: Complete Video Course & Book
- While Loops, And The General Range — Hands-on Python: Complete Video Course & Book
- Interactive While Loops — Hands-on Python: Complete Video Course & Book
- Chapter Three In One Sitting — Hands-on Python: Complete Video Course & Book
- While, For, Range And The Loop Else — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Control Flow Sprint — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Twelve Traps, One Shape Each — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
References
- Bash Reference Manual: Looping Constructs
- Python tutorial: first steps towards programming
- Compound statements: while