Bash/Parsing things

From Linux Hints

Jump to: navigation, search

Usually, there are lots of ways of parsing something, with various pros and cons. My preference is to use bash with a combination sed, cut and grep. I'm not really an awk or Perl person.

Get a valid integer

Since the test operaters such as -lt, -gt, etc, complain if you pass a non integer, you need to check beforehand. This will return number if it's valid, or nothing if not:

val=$(echo $val | grep -E '^[+-]?[0-9]+$' || true)

Then you can use:

if [ -z "$val" ] ; then 
  echo "Number is invalid"
elif [ "$val" -lt 0 -o "$val" -gt 10 ] ; then
  echo "Value is out of range"
fi

This won't strip leading zeroes, however. For that, this is one way:

val=$(($val + 0))
Personal tools
related