Watch a disk alert fail at 100 percent
Task
Reproduce the string-versus-numeric comparison bug in the exact form that matters: a disk alert that works at 95% and silently stops working at 100%. Then map the operator families and confirm where <= actually lives.
Steps
- Write the broken check:
used=100; if [[ "$used" > "90" ]]; then echo ALERT; fi. Confirm it does NOT alert, and explain why "100" sorts before "90". - Run the same check with
used=95and confirm it DOES alert. This is the trap: it works for most values and fails at the one that matters most. - Fix it with the numeric operator:
[[ "$used" -gt 90 ]], and confirm it alerts correctly at both 95 and 100. - Feed a numeric operator a word, and compare the two test commands:
[ "abc" -gt 5 ]fails LOUDLY -- "integer expected", exit status 2. But[[ "abc" -gt 5 ]]says nothing and returns 1, because inside[[ ]]the operands of-gtare arithmetic, and in arithmetic a bare word is a VARIABLE NAME: unset, so 0. Prove it:abc=10; [[ "abc" -gt 5 ]] && echo trueprints true. The single-bracket form is the one that tells you the input was not a number; the double-bracket form quietly answers a different question. - Confirm
<=is arithmetic, not a string operator:[[ 5 <= 9 ]]is a syntax error, while(( 5 <= 9 ))works. Explain the mapping. - Demonstrate return codes: run a command that fails, capture
$?immediately into a variable, and show that testing$?one line too late tests theechoin between. - Recognise exit 137: run
bash -c 'kill -9 $$'in a subshell and read the 137 that 128+9 produces.
Verify
cd ~/lab-ops
used=100; [[ "$used" > "90" ]] && echo "string: alerts" || echo "string: SILENT at 100"
used=100; [[ "$used" -gt 90 ]] && echo "numeric: alerts correctly"
( bash -c 'kill -9 $$'; echo "exit $?" ) | tail -1 # 137
[ "abc" -gt 5 ] 2>/dev/null; echo "single bracket: $?" # 2 -- an error
[[ "abc" -gt 5 ]]; echo "double bracket: $?" # 1 -- silent
The first line printing "SILENT at 100" is the whole lab: the wrong operator family gives a wrong answer, not an error, and it fails precisely when the disk is fullest.
Notes
The families do not mix. -gt -lt -eq compare numbers; > < = == compare strings; <= >= are arithmetic and live only in (( )). CompTIA's own objective list prints the regex operator as "= ~" and inequality as "! =" with spaces -- both are typos, and a space breaks either.
This is an independent study companion for CompTIA Linux+ and is not produced by or endorsed by CompTIA.