Skip to content

Instantly share code, notes, and snippets.

@ip1981
Last active December 19, 2018 17:18
Show Gist options
  • Save ip1981/0dc352408fc9395327cef65f8b414c60 to your computer and use it in GitHub Desktop.
Save ip1981/0dc352408fc9395327cef65f8b414c60 to your computer and use it in GitHub Desktop.
Parse Nagios plugins ranges in Bash. Only integers
#!/usr/bin/env bash
# Parse Nagios plugins ranges in Bash. Only integers.
# https://nagios-plugins.org/doc/guidelines.html#THRESHOLDFORMAT
set -euo pipefail
inrange () {
local r v
local v1 v2
local outter
local sIFS
r="$1"
v="$2"
case "$r" in
@*) outter=true; r="${r/@/}";;
*) outter=false;;
esac
sIFS=$IFS
IFS=:
set -- $r
v1=${1-}
v2=${2-}
IFS=$sIFS
case "$v1" in
$r) v2=$v1; v1=0;;
~*) v1=;;
esac
if $outter; then
{ [ -n "$v1" ] && [ "$v" -le "$v1" ]; } || { [ -n "$v2" ] && [ "$v" -ge "$v2" ]; }
else
{ [ -z "$v1" ] || [ "$v" -ge "$v1" ]; } && { [ -z "$v2" ] || [ "$v" -le "$v2" ]; }
fi
}
test_inrange () {
printf "%s ~~ %s\t" $2 $1
if inrange "$1" "$2"; then
printf 'IN '
if $3; then
echo '- OK'
else
echo '- FAILED'
fi
else
printf 'OUT '
if $3; then
echo '- FAILED'
else
echo '- OK'
fi
fi
}
test_inrange '-123:456' 222 true
test_inrange '-456:-123' -222 true
test_inrange '123' -22 false
test_inrange '123' 1 true
test_inrange '123' 222 false
test_inrange '123:' 222 true
test_inrange '123:456' 222 true
test_inrange '123:456' 2222 false
test_inrange ':-123' 2 false
test_inrange ':-456' -222 false
test_inrange ':-456' -2222 true
test_inrange ':-456' 222 false
test_inrange ':456' 222 true
test_inrange ':456' 2222 false
test_inrange '@123' -222 true
test_inrange '@123' 222 true
test_inrange '@123:456' -222 true
test_inrange '@123:456' 222 false
test_inrange '@:456' 222 false
test_inrange '@:456' 2222 true
test_inrange '@~:-123' -222 false
test_inrange '@~:-123' 222 true
test_inrange '~:-123' -222 true
test_inrange '~:-123' 222 false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment