While hardening a portable backup script, a systems administrator needs the script to rotate logs only when the current log volume (in MB) stored in variable SIZE exceeds the configured maximum stored in MAX. The existing Bourne-shell code is:
if [ "$SIZE" > "$MAX" ]; then
/usr/local/bin/rotate_logs
fi
During testing, the shell treats the > symbol as an output-redirection operator and the comparison fails. The script must stay POSIX-compliant and run under /bin/sh. Which replacement will correctly perform the numeric comparison?
Escape the operator: if [ "$SIZE" \> "$MAX" ]; then
Replace the condition with if [ "$SIZE" -gt "$MAX" ]; then
Use arithmetic evaluation: if (( SIZE > MAX )); then
Replace the condition with if [ "$SIZE" -ge "$MAX" ]; then
Inside the single-bracket test command ([ ]) a numeric comparison must use the arithmetic primaries defined by POSIX. The operator -gt evaluates whether the first integer is greater than the second, matching the requirement that the size "exceeds" the limit. -ge would also allow the values to be equal, which is not requested. Escaping > still leaves a lexicographical string comparison, not a numeric one. The double-parentheses form (( SIZE > MAX )) is a Bash extension and is not guaranteed to work in a strictly POSIX /bin/sh script. Therefore, changing the line to if [ "$SIZE" -gt "$MAX" ]; then is the only portable fix.
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 POSIX-compliant mean?
Open an interactive chat with Bash
What is the difference between `-gt` and `>` in shell scripting?