The while loop must have 'do' after the condition to start the loop body.
Step 2: Identify missing 'do'
The script misses 'do' after the condition line, causing syntax error.
Final Answer:
Missing 'do' keyword after while condition -> Option C
Quick Check:
while loop needs 'do' [OK]
Hint: Always put 'do' after while condition [OK]
Common Mistakes:
Omitting 'do' keyword
Misplacing brackets
Incorrect increment syntax
5. You want to write a bash script that prints all even numbers from 2 to 10 using a while loop. Which script correctly does this?
hard
A. num=1
while [ $num -le 10 ]; do
if [ $((num % 2)) -eq 0 ]; then echo $num; fi
num=$((num + 1))
done
B. num=2
while [ $num -le 10 ]; do
echo $num
num=$((num + 1))
done
C. num=2
while [ $num -lt 10 ]; do
echo $num
num=$((num + 2))
done
D. num=0
while [ $num -le 10 ]; do
echo $num
num=$((num + 2))
done
Solution
Step 1: Understand the goal
We want to print even numbers from 2 to 10 inclusive.
Step 2: Check each option's logic
num=2
while [ $num -le 10 ]; do
echo $num
num=$((num + 1))
done starts at 2 and increments by 1 up to 10, printing 2 3 4 5 6 7 8 9 10 - incorrect. num=1
while [ $num -le 10 ]; do
if [ $((num % 2)) -eq 0 ]; then echo $num; fi
num=$((num + 1))
done starts at 1, increments by 1, and prints only if even - correct. num=2
while [ $num -lt 10 ]; do
echo $num
num=$((num + 2))
done stops before 10, missing 10. num=0
while [ $num -le 10 ]; do
echo $num
num=$((num + 2))
done starts at 0, which is even but outside requested range (2 to 10).
Step 3: Choose the best option
Only the script using modulo to explicitly check evenness prints exactly 2,4,6,8,10.
Final Answer:
num=1
while [ $num -le 10 ]; do
if [ $((num % 2)) -eq 0 ]; then echo $num; fi
num=$((num + 1))
done -> Option A
Quick Check:
Check even with modulo inside loop [OK]
Hint: Use modulo inside loop to print even numbers [OK]
Common Mistakes:
Stopping loop before 10
Starting from 0 when 2 is required
Not checking evenness explicitly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.