⇤ ← Revision 1 as of 2023-01-20 17:25:53
Size: 137
Comment:
|
Size: 1200
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 11: | Line 11: |
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 [[Shell/Expansion|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 }}} |
|
Line 17: | Line 35: |
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 }}} ---- == 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 }}} |
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
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
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