Bird
0
0

You want to run a script that prints "Even" if a number is divisible by 2, otherwise "Odd". Which script correctly uses conditionals?

hard🚀 Application Q8 of 15
Bash Scripting - Conditionals
You want to run a script that prints "Even" if a number is divisible by 2, otherwise "Odd". Which script correctly uses conditionals?
A#!/bin/bash num=4 if [ $(num % 2) -eq 0 ]; then echo "Even" else echo "Odd" fi
B#!/bin/bash num=4 if (( $num % 2 == 0 )); then echo "Even" else echo "Odd" fi
C#!/bin/bash num=4 if [ $num % 2 == 0 ]; then echo "Even" else echo "Odd" fi
D#!/bin/bash num=4 if [ $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 (( )) allows arithmetic expressions and comparisons.
  2. Step 2: Check each option's syntax

    #!/bin/bash num=4 if (( $num % 2 == 0 )); then echo "Even" else echo "Odd" fi correctly uses (( $num % 2 == 0 )). #!/bin/bash num=4 if [ $((num % 2)) -eq 0 ]; then echo "Even" else echo "Odd" fi uses incorrect syntax inside [ ]. #!/bin/bash num=4 if [ $num % 2 == 0 ]; then echo "Even" else echo "Odd" fi uses invalid operator inside [ ]. #!/bin/bash num=4 if [ $num / 2 -eq 0 ]; then echo "Even" else echo "Odd" fi uses division instead of modulo.
  3. Final Answer:

    (( $num % 2 == 0 )) syntax -> Option B
  4. Quick Check:

    Use (( )) for arithmetic tests = C [OK]
Quick Trick: Use (( )) for math conditions in bash [OK]
Common Mistakes:
MISTAKES
  • Using % inside [ ]
  • Using == inside [ ]
  • Confusing / with %

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes