Challenge - 5 Problems
If-Then-Else Bash Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
Output of nested if-then-else in Bash
What is the output of this Bash script when run?
#!/bin/bash
x=5
if [ $x -gt 3 ]; then
if [ $x -lt 10 ]; then
echo "Between 4 and 9"
else
echo "10 or more"
fi
else
echo "3 or less"
fiBash Scripting
#!/bin/bash x=5 if [ $x -gt 3 ]; then if [ $x -lt 10 ]; then echo "Between 4 and 9" else echo "10 or more" fi else echo "3 or less" fi
Attempts:
2 left
💡 Hint
Check the conditions step by step and see which echo runs.
✗ Incorrect
The variable x is 5, which is greater than 3 and less than 10, so the inner if condition is true and prints 'Between 4 and 9'.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in this if-then-else script
Which option shows the correct way to fix the syntax error in this Bash script?
#!/bin/bash x=10 if [ $x -eq 10 ] echo "x is 10" else echo "x is not 10" fi
Bash Scripting
#!/bin/bash x=10 if [ $x -eq 10 ] echo "x is 10" else echo "x is not 10" fi
Attempts:
2 left
💡 Hint
Bash requires 'then' after the if condition.
✗ Incorrect
The if statement must be followed by 'then' to be syntactically correct.
🔧 Debug
advanced2:00remaining
Why does this if-then-else script always print 'No'?
Consider this Bash script:
Why does it always print "No" even if var is empty?
#!/bin/bash var="" if [ $var ]; then echo "Yes" else echo "No" fi
Why does it always print "No" even if var is empty?
Bash Scripting
#!/bin/bash var="" if [ $var ]; then echo "Yes" else echo "No" fi
Attempts:
2 left
💡 Hint
Check how Bash treats empty strings inside [ ]
✗ Incorrect
In Bash, [ $var ] tests if $var is non-empty. If empty, condition is false and else runs.
🚀 Application
advanced2:00remaining
What is the output of this if-then-else with arithmetic test?
What does this Bash script print?
#!/bin/bash num=7 if (( num % 2 == 0 )); then echo "Even" else echo "Odd" fi
Bash Scripting
#!/bin/bash num=7 if (( num % 2 == 0 )); then echo "Even" else echo "Odd" fi
Attempts:
2 left
💡 Hint
Check if 7 is divisible by 2
✗ Incorrect
7 modulo 2 is 1, so condition is false and else block prints 'Odd'.
🧠 Conceptual
expert3:00remaining
How many times does this loop print 'Hello'?
Analyze this Bash script:
How many times will "Hello" be printed?
#!/bin/bash
count=0
while [ $count -lt 3 ]; do
if [ $count -eq 1 ]; then
count=$((count + 2))
else
count=$((count + 1))
fi
echo "Hello"
doneHow many times will "Hello" be printed?
Bash Scripting
#!/bin/bash count=0 while [ $count -lt 3 ]; do if [ $count -eq 1 ]; then count=$((count + 2)) else count=$((count + 1)) fi echo "Hello" done
Attempts:
2 left
💡 Hint
Trace the value of count each loop iteration.
✗ Incorrect
Loop runs while count < 3. Iterations: count=0 -> print, count=1 -> print and add 2 (count=3), loop ends. So prints twice.