← Lessons/Loops & Conditionals
← Loops & Conditionals

Only the even ones

Learn

Arithmetic with (( … )), inside the loop

To compare or compute numbers, use the arithmetic construct (( … )). Inside it you write maths the way you'd expect: no $ needed on variables, and the usual operators work.

if (( n % 3 == 0 )); then
  echo "$n is divisible by 3"
fi

% is modulo, the remainder after division, so n % 2 == 0 is the standard "is this even?" test. (( … )) succeeds when the expression is true, which is exactly what if wants. Use (( … )) for numbers and [ … ] for files and strings.

Nest the test inside a loop and you get "for each item, but only when…": the core engine of shell automation.

The editor opens with your loop from the previous step. This step checks the output exactly, so change the loop rather than adding a second one.

Loop over 1 through 5 and print only the even numbers, using arithmetic to decide (an if, or the && short form — either is fine). The output should be exactly two lines: 2 then 4.

Interview prep

Control flow shows you can actually script, not just run commands.

When would you reach for a while loop instead of a for loop?

for is for a known list (files, a range). while runs until a condition changes — reading a stream line by line, retrying until something succeeds, polling until a service is up.

$ bash solution.sh
Loading...

Output

Run your solution to see its output here.