A startup script records the current number of logged-in users in the variable session_count and is supposed to trigger an automatic scale-out when this integer value exceeds 50:
session_count=$(who | wc -l)
# TODO: trigger scale-out when sessions > 50
if [ "$session_count" > 50 ]; then
scale_out
fi
During testing, scale_out sometimes runs even when session_count is only 9. Which replacement for the if line performs the intended numeric comparison portably in any POSIX-compliant shell and avoids run-time errors?
The POSIX‐defined test (or [ … ]) command uses the -gt primary for an integer greater-than test. Quoting the variable prevents a syntax error if the value is empty or contains whitespace. Therefore:
if [ "$session_count" -gt 50 ]; then
returns a true exit status only when session_count is an integer larger than 50.
Why the other choices are wrong:
[[ $session_count > 50 ]] - Within [[ … ]], the unquoted > operator performs a string (lexicographic) comparison, not numeric; "9" sorts after "50", so the condition can be true when the count is only one digit.
(( session_count > 50 )) - Arithmetic evaluation works, but the (( … )) construct is a Bash/Ksh extension, not required by POSIX; a strictly POSIX shell may not recognize it.
[ $session_count -gt 50 ] - Omits quotes around the variable; if session_count is empty or contains non-digits the shell expands the test to [ -gt 50 ], producing the run-time error "integer expression expected" (or "unary operator expected") and breaking the script.
Thus the quoted -gt test is the only option that is both numerically correct and fully portable.
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 `-gt` operator do in a POSIX shell?
Open an interactive chat with Bash
Why is quoting variables important in shell scripts?
Open an interactive chat with Bash
What is the difference between `[ … ]` and `[[ … ]]` in shell scripting?
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