Bird
0
0

You want to check if a script received exactly two arguments and print a message with the script name and arguments. Which snippet correctly uses special variables?

hard🚀 Application Q9 of 15
Bash Scripting - Variables
You want to check if a script received exactly two arguments and print a message with the script name and arguments. Which snippet correctly uses special variables?
Aif [ "$?" -eq 2 ]; then echo "Script $0 got args: $1 and $2"; fi
Bif [ "$#" -eq 2 ]; then echo "Script $0 got args: $1 and $2"; fi
Cif [ "$@" -eq 2 ]; then echo "Script $0 got args: $1 and $2"; fi
Dif [ "$0" -eq 2 ]; then echo "Script $0 got args: $1 and $2"; fi
Step-by-Step Solution
Solution:
  1. Step 1: Identify variable holding argument count

    $# holds the number of arguments passed to the script.
  2. Step 2: Use correct test syntax

    The test [ "$#" -eq 2 ] checks if exactly two arguments were passed.
  3. Final Answer:

    Use $# to check argument count and $1, $2 for arguments -> Option B
  4. Quick Check:

    $# = argument count [OK]
Quick Trick: Use $# to count args; $1, $2 to access them [OK]
Common Mistakes:
MISTAKES
  • Using $@ or $? instead of $# for count
  • Comparing string variables with -eq incorrectly
  • Using $0 (script name) as argument count

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes