Bird
0
0

You want to write a script that prints "Positive" if a number is greater than zero, "Zero" if it is zero, and "Negative" otherwise. Which of these scripts correctly implements this using elif?

hard🚀 Application Q8 of 15
Bash Scripting - Conditionals
You want to write a script that prints "Positive" if a number is greater than zero, "Zero" if it is zero, and "Negative" otherwise. Which of these scripts correctly implements this using elif?
A#!/bin/bash num=5 if [ $num -gt 0 ]; then echo "Positive" else echo "Zero" else echo "Negative" fi
B#!/bin/bash num=5 if [ $num -gt 0 ]; then echo "Positive" else if [ $num -eq 0 ]; then echo "Zero" else echo "Negative" fi
C#!/bin/bash num=5 if [ $num -gt 0 ]; then echo "Positive" else if [ $num -eq 0 ]; then echo "Zero" else echo "Negative" fi fi
D#!/bin/bash num=5 if [ $num -gt 0 ]; then echo "Positive" elif [ $num -eq 0 ]; then echo "Zero" else echo "Negative" fi
Step-by-Step Solution
Solution:
  1. Step 1: Check correct use of elif

    #!/bin/bash num=5 if [ $num -gt 0 ]; then echo "Positive" elif [ $num -eq 0 ]; then echo "Zero" else echo "Negative" fi uses elif correctly to check the second condition.
  2. Step 2: Identify errors in other options

    #!/bin/bash num=5 if [ $num -gt 0 ]; then echo "Positive" else if [ $num -eq 0 ]; then echo "Zero" else echo "Negative" fi uses invalid "else if" syntax; #!/bin/bash num=5 if [ $num -gt 0 ]; then echo "Positive" else if [ $num -eq 0 ]; then echo "Zero" else echo "Negative" fi fi nests if inside else correctly but is more complex; #!/bin/bash num=5 if [ $num -gt 0 ]; then echo "Positive" else echo "Zero" else echo "Negative" fi has two else blocks which is invalid.
  3. Final Answer:

    Script with elif -> Option D
  4. Quick Check:

    Use elif for multiple conditions [OK]
Quick Trick: Use elif for multiple conditions, not else if [OK]
Common Mistakes:
MISTAKES
  • Using else if instead of elif
  • Multiple else blocks
  • Not closing nested if with fi

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes