While writing an emergency POSIX shell script (#!/bin/sh), you need to run a loop only when the variable COUNT is less-or-equal to 50. COUNT may sometimes be unset or an empty string. Which test expression should you place in the loop condition so the script stays portable and does not throw a "unary operator expected" error on minimal systems?
The single-bracket test command (the [ builtin) is specified by POSIX and is available in every /bin/sh implementation. Using the numeric operator -le performs an integer "less than or equal" comparison. Double-quoting the variable suppresses word splitting and pathname expansion and ensures that an empty value is passed as a blank string instead of disappearing, which would make the operator lose its left-hand operand and raise the "unary operator expected" error. The other choices all have drawbacks:
[[ $COUNT -le 50 ]] relies on the Bash-specific double-bracket construct and is not guaranteed to exist in a rescue /bin/sh.
(( COUNT <= 50 )) uses arithmetic evaluation that many POSIX shells (for example dash or the original Bourne shell) do not implement.
[ $COUNT -le 50 ] omits the protective quotes; if COUNT is empty or contains spaces, the test receives the wrong number of arguments and can fail with the same unary-operator error the question seeks to avoid. Therefore, quoting the variable inside the portable single-bracket test is the only safe and universally compatible solution.
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.
Why is double-quoting variables important in shell scripts?
Open an interactive chat with Bash
What makes the `[` (single-bracket) test command more portable than `[[` or `((`?
Open an interactive chat with Bash
What are some common errors caused by unquoted variables in shell scripts?
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