Linux command
while 命令
文本
涉及管道、覆盖或删除,执行前请先确认路径和参数。
常用示例
Basic while loop
while [condition]; do [command]; done
Infinite loop
while true; do [command]; sleep [1]; done
Read file line by line
while read -r line; do echo "$line"; done < [file.txt]
Loop until command fails
while [command]; do echo "still running"; done
Counter loop
i=0; while [ $i -lt 10 ]; do echo $i; i=$((i+1)); done
Process command output
[command] | while read -r line; do echo "$line"; done
Loop with break
while true; do if [condition]; then break; fi; done
说明
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.
参数
- 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.
FAQ
What is the while command used for?
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.
How do I run a basic while example?
Run `while [condition]; do [command]; done` in a terminal, then adjust file names, paths, flags, or remote targets for your system.
What does break do in while?
Exit the loop immediately.