Bird
0
0

You want a script that prints "Even" if a number is even, and "Odd" if it is odd. Which script correctly uses if-then-else to do this?

hard🚀 Application Q15 of 15
Bash Scripting - Conditionals
You want a script that prints "Even" if a number is even, and "Odd" if it is odd. Which script correctly uses if-then-else to do this?
num=4
# Choose correct script
Aif [ $num % 2 -eq 0 ]; then echo "Even" else echo "Odd" fi
Bif (( num % 2 == 0 )); then echo "Even" else echo "Odd" fi
Cif [ $num % 2 == 0 ]; then echo "Even" else echo "Odd" fi
Dif [ $num / 2 -eq 0 ]; then echo "Even" else echo "Odd" fi
Step-by-Step Solution
Solution:
  1. Step 1: Understand arithmetic evaluation in bash

    Using double parentheses (( )) allows arithmetic expressions and comparisons directly.
  2. Step 2: Check each option

    if [ $num % 2 -eq 0 ]; then echo "Even" else echo "Odd" fi uses % inside [ ] without arithmetic evaluation. if [ $num % 2 == 0 ]; then echo "Even" else echo "Odd" fi uses % inside [ ] without arithmetic evaluation. if [ $num / 2 -eq 0 ]; then echo "Even" else echo "Odd" fi uses / instead of % for modulus. if (( num % 2 == 0 )); then echo "Even" else echo "Odd" fi correctly uses (( )) with modulus and comparison.
  3. Final Answer:

    if (( num % 2 == 0 )); then echo "Even" else echo "Odd" fi -> Option B
  4. Quick Check:

    Use (( )) for arithmetic if [OK]
Quick Trick: Use (( )) for math conditions in bash [OK]
Common Mistakes:
MISTAKES
  • Using [ ] with arithmetic operators incorrectly
  • Confusing / with % for modulus
  • Missing then keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes