Shell Looping


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.


CategoryRicottone

Shell/Looping (last edited 2023-01-25 21:45:31 by DominicRicottone)