>_ IzzyLab

Hands-on task

This task is step 7 of the course “Clean scripts: shellcheck”

Compare numbers as numbers

medium~7 min

The script /root/cmp.sh compares the numbers 9 and 10 with a string operator and wrongly decides that 9 is greater than 10. Fix the comparison to be numeric, so the script prints smaller and shellcheck is clean.

What you'll practise:
  • shellcheck
  • numeric comparison
  • SC2071
  • (( ))
  • -gt

Topic breakdown

Bash has two different worlds of comparison. String operators (=, !=, <, > inside [[ ]]) compare by character order, so "9" > "10". Numeric comparisons are done by the arithmetic context (( a > b )) or by the test operators: -eq -ne -gt -lt -ge -le. Mixing them up silently gives wrong results on multi-digit numbers; shellcheck warns with rule SC2071 when it sees >/< where numbers are clearly meant.

What's checked

  1. shellcheck reports nothing
  2. 9 is less than 10
  3. the comparison works with other numbers too

What it looks like