Bash: Numeric comparison

From FVue

Jump to: navigation, search

Problem

The following tests – using greater than (>) – do not work:

$     # Redirects to file `5'.  Returns true unexpected.
$ [ 3 > 5 ] && echo true  # Wrong
true
$     # Does string - not numeric - comparison.  Returns true unexpected.
$ [[ 5 > 34 ]] && echo true  # Wrong
true
$

Solution

Always use the -eq, -ne, -lt, -le, -gt, or -ge arithmetic binary operators for numeric comparison. For example:

$ [ 3 -gt 5 ] && echo true
$ [[ 5 -gt 34 ]] && echo true
$
Personal tools