Size: 1523
Comment:
|
← Revision 5 as of 2023-01-25 21:45:31 ⇥
Size: 1784
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 29: | Line 29: |
To immediately skip to the next iteration, use the `continue` [[Shell/BuiltinCommands#Continue|builtin]]. | To immediately skip to the next iteration, use the `continue` [[Shell/BuiltinCommands#Continue|builtin]]. To immediately exit the loop, use the `break` [[Shell/BuiltinCommands#Break|builtin]]. |
Line 48: | Line 48: |
To immediately skip to the next iteration, use the `continue` [[Shell/BuiltinCommands#Continue|builtin]]. | To immediately skip to the next iteration, use the `continue` [[Shell/BuiltinCommands#Continue|builtin]]. To immediately exit the loop, use the `break` [[Shell/BuiltinCommands#Break|builtin]]. |
Line 72: | Line 72: |
To immediately skip to the next iteration, use the `continue` [[Shell/BuiltinCommands#Continue|builtin]]. | To immediately skip to the next iteration, use the `continue` [[Shell/BuiltinCommands#Continue|builtin]]. To immediately exit the loop, use the `break` [[Shell/BuiltinCommands#Break|builtin]]. |
Shell Looping
Contents
For Loops
The for loop iterates over a list. The list can be anything from a literal list of items (1 2 3) to a process expansion ($(seq 1 3)) to a filename expansion (*). See here for more details.
for filename in *; do chmod 755 "$filename" done
If a list is not specified, sh(1) implicitly loops over "$@".
for arg; do if [ "$arg" = "-h" ]; then echo "$help_message" fi done
To immediately skip to the next iteration, use the continue builtin. To immediately exit the loop, use the break builtin.
While Loops
The while loop iterates as long as the condition evaluates to true.
As an example, to infinitely loop and execute a command every 5 seconds, try:
while true; do date sleep 5 done
To immediately skip to the next iteration, use the continue builtin. To immediately exit the loop, use the break builtin.
Until Loops
until loops are the inverse of a while loops.
As an example, to repeatedly prompt a user until a valid response is detected, try:
echo "Create file 'config.toml'? [y/N]: " until [ -e "config.toml" ]; do read RESPONSE case "$RESPONSE" in [Yy]) touch "config.toml";; [Nn]) exit 1;; *) echo "Please enter Y or N";; esac done
To immediately skip to the next iteration, use the continue builtin. To immediately exit the loop, use the break builtin.