What happens when the condition in the 'until' loop is initially true?

QuestionsQuestions8 SkillsProDec, 20 2025
0102

If the condition in an until loop is initially true, the code block inside the loop will not execute even once.

This is because Bash checks the condition before entering the loop. Since the logic of an until loop is "Keep doing this until the condition becomes true," if it finds the condition is already true at the very start, it simply skips over the loop entirely.

Example:

Imagine you change your until_loop.sh to start with a count that is already greater than 5:

#!/bin/bash

count=10
echo "Starting the loop..."

# The condition is: Is count greater than 5? 
# Since 10 is already > 5, this is TRUE immediately.
until [ $count -gt 5 ]; do
  echo "This message will never be seen."
  count=$((count + 1))
done

echo "Loop finished!"

Output:

Starting the loop...
Loop finished!

Comparison with while

  • while loop: Runs as long as the condition is True. If it's initially False, it never runs.
  • until loop: Runs as long as the condition is False. If it's initially True, it never runs.

In both cases, they are "pre-test" loops, meaning the condition is verified before the loop's body is executed.

0 Comments

no data
Be the first to share your comment!