A system administrator is writing a script that requires exactly one command-line argument to function correctly. If the script is run with zero arguments or more than one argument, it should print a usage message and exit.
Which of the following conditional statements correctly checks if the number of arguments is NOT equal to one?
The correct answer uses the special variable $# and the numerical comparison operator -ne. The $# variable holds the count of positional parameters passed to the script. The -ne operator is used within a test ([ ]) expression to check if two numbers are not equal. Therefore, the expression [ $# -ne 1 ] will evaluate to true if the number of arguments is anything other than one.
[ $@ -ne 1 ] is incorrect because $@ expands to the list of all positional parameters, not the count of them. It is unsuitable for a numerical comparison.
[ $# != 1 ] is incorrect because != is the operator for string comparison, not numerical comparison. While some shells might handle this, -ne is the standard and correct operator for numerical tests.
[ -z "$1" ] is incorrect because it tests if the first positional parameter ($1) is an empty string. This does not correctly check if the number of arguments is exactly one; for example, it would fail if the script was called with two arguments.
Ask Bash
Bash is our AI bot, trained to help you pass your exam. AI Generated Content may display inaccurate information, always double-check anything important.
What is the purpose of the special variable `$#` in a script?
Open an interactive chat with Bash
Why is `-ne` preferred over `!=` for numerical comparisons in scripts?
Open an interactive chat with Bash
What does the `$@` variable represent, and why is it unsuitable for counting arguments?
Open an interactive chat with Bash
CompTIA Linux+ XK0-006 (V8)
Automation, Orchestration, and Scripting
Your Score:
Report Issue
Bash, the Crucial Exams Chat Bot
AI Bot
Loading...
Loading...
Loading...
IT & Cybersecurity Package Join Premium for Full Access