0
0
Bash Scriptingscripting~20 mins

if-then-else in Bash Scripting - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
If-Then-Else Bash Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2: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"
fi
Bash 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
ABetween 4 and 9
B10 or more
C3 or less
DSyntax error
Attempts:
2 left
💡 Hint
Check the conditions step by step and see which echo runs.
📝 Syntax
intermediate
2: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
AAdd 'then' after the if condition: if [ $x -eq 10 ]; then
BAdd a semicolon after echo statement
CReplace 'fi' with 'end'
DRemove the else block
Attempts:
2 left
💡 Hint
Bash requires 'then' after the if condition.
🔧 Debug
advanced
2:00remaining
Why does this if-then-else script always print 'No'?
Consider this Bash script:
#!/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
ABecause the script has a syntax error
BBecause [ $var ] is false when var is empty, so else runs
CBecause var is not defined
DBecause echo is not inside the if block
Attempts:
2 left
💡 Hint
Check how Bash treats empty strings inside [ ]
🚀 Application
advanced
2: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
ASyntax error
BEven
COdd
DNo output
Attempts:
2 left
💡 Hint
Check if 7 is divisible by 2
🧠 Conceptual
expert
3:00remaining
How many times does this loop print 'Hello'?
Analyze this Bash script:
#!/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

How 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
A4
B3
CInfinite loop
D2
Attempts:
2 left
💡 Hint
Trace the value of count each loop iteration.