A portable Bourne-shell (#!/bin/sh) start-up script must enable verbose output only when the variable $LOGLEVEL is exactly "DEBUG". The sysadmin tried the following code, which works under Bash but fails with the message ": ==: unexpected operator" on several older systems:
if [ "$LOGLEVEL" == "DEBUG" ]; then
VERBOSE=true
fi
Which single change will make the condition POSIX-compliant and eliminate the error without introducing any non-standard syntax or external commands?
Use the numeric comparison operator:
if [ "$LOGLEVEL" -eq "DEBUG" ]; then
VERBOSE=true
fi```
Change the operator to a single equals sign:
if [ "$LOGLEVEL" = "DEBUG" ]; then
VERBOSE=true
fi```
Escape the double-equals operator to force literal parsing:
if [ "$LOGLEVEL" \== "DEBUG" ]; then
VERBOSE=true
fi```
Replace the brackets with Bash's conditional expression:
if [[ "$LOGLEVEL" == "DEBUG" ]]; then
VERBOSE=true
fi```
The single-bracket test command (a synonym for the POSIX test utility) recognizes the "=" operator for string equality but does not require support for "". When /bin/sh on a platform lacks the non-standard "" extension it reports an error such as "unexpected operator". Replacing the operator with the POSIX-mandated single equals sign produces a portable comparison that works in any conforming shell:
if [ "$LOGLEVEL" = "DEBUG" ]; then
VERBOSE=true
fi
Switching to the double-bracket form ([[ … ]]) would also work in Bash, but that syntax is a Bash/Korn-shell extension and is not available in a strictly POSIX /bin/sh. Using -eq is for numeric tests, so it will always fail (and may emit "integer expression expected"). Escaping the double equals (\==) does not change the fact that the operator itself is unrecognized. Therefore only the single equals sign inside the original [ … ] test provides the required portable, standards-compliant string comparison.
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 POSIX and why is it important for scripting?
Open an interactive chat with Bash
Why does '==' fail in older systems while '=' works?
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