>_ IzzyLab

Hands-on task

This task is step 6 of the course “Your first bash script”

if: compare a number with a threshold

easy~6 min

Monitoring passes the script how full the disk is, in percent — a whole number from 0 to 100. Write /root/disk-alert.sh: if the number in the first argument is greater than 80, the script prints ALERT, otherwise OK.

$ bash disk-alert.sh 93
ALERT
$ bash disk-alert.sh 80
OK
$ bash disk-alert.sh 42
OK

Exactly 80 isn't an alert yet.

What you'll practise:
  • bash scripts
  • if
  • comparing numbers
  • -gt

Topic breakdown

Inside [ ] numbers are compared not with symbols but with letter operators:

| Operator | Means | |---|---| | -eq | equal | | -ne | not equal | | -gt | greater than | | -ge | greater than or equal | | -lt | less than | | -le | less than or equal |

if [ "$1" -lt 10 ]; then
    echo "less than ten"
else
    echo "ten or more"
fi

Why not >: inside [ ] the > sign is output redirection. [ "$1" > 10 ] compares nothing — it creates a file named 10, and the condition is always true. And [[ "$1" > 10 ]] compares strings "alphabetically", where 9 is greater than 10 because 9 comes after 1.

Another way to compare numbers is double parentheses: if (( $1 < 10 )). Inside them < and > work as in math.

What's checked

  1. /root/disk-alert.sh created
  2. Numbers above the threshold give ALERT
  3. The threshold and numbers below it give OK

What it looks like