[Bash] while & until commands

Zhentiw發表於2024-05-21

While

The while loop executes a block of code as long as a specified condition is true.

while [ condition ]; do
  commands
done

Example:

#!/bin/zsh

count=1
while [ $count -le 5 ]; do
  echo "Count: $count"
  count=$((count + 1))
done

Until

The until loop executes a block of code as long as a specified condition is false.

until [ condition ]; do
  commands
done

Example:

#!/bin/zsh

target=7
guess=0

until [ $guess -eq $target ]; do
  echo "Guess the number: "
  read guess
  if [ $guess -lt $target ]; then
    echo "Too low!"
  elif [ $guess -gt $target ]; then
    echo "Too high!"
  else
    echo "Correct!"
  fi
done

相關文章