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 does the `$#` variable represent in a shell script?
Open an interactive chat with Bash
What is the difference between the `-ne` and `!=` operators in shell scripting?
Open an interactive chat with Bash
Why is `[ $@ -ne 1 ]` incorrect when checking the number of 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...
Pass with Confidence.
IT & Cybersecurity Package
You have hit the limits of our free tier, become a Premium Member today for unlimited access.
Military, Healthcare worker, Gov. employee or Teacher? See if you qualify for a Community Discount.
Monthly
$19.99
$19.99/mo
Billed monthly, Cancel any time.
3 Month Pass
$44.99
$14.99/mo
One time purchase of $44.99, Does not auto-renew.
MOST POPULAR
Annual Pass
$119.99
$9.99/mo
One time purchase of $119.99, Does not auto-renew.
BEST DEAL
Lifetime Pass
$189.99
One time purchase, Good for life.
What You Get
All IT & Cybersecurity Package plans include the following perks and exams .