0

I am adding two numbers using the below script, but I don't want non-numeric character entry from user so I need to test and throw an error. How do I test the user entry?

echo add 2 numbers
read sum1
read sum2
let sum3=$sum1+$sum2
echo ans is $sum3
Paul
  • 26,170
  • 12
  • 85
  • 119
Vinoth
  • 5
  • 1
  • possible duplicate of [BASH: Test whether string is valid as an integer?](http://stackoverflow.com/questions/2210349/bash-test-whether-string-is-valid-as-an-integer) – Adrian Frühwirth Jun 12 '14 at 08:00

1 Answers1

1

Use printf for testing if variable is valid integer:

isInt() {
    [[ -n "$1" ]] && printf '%f' "$1" >/dev/null 2>&1 && 
                  echo "valid integer" || echo "invalid integer";
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • i used declare -i as below,

    `#/bin/bash
    ` `echo integer testing;
    ` `read no;
    ` `declare -i iint=$no
    ` `[ $iint = "$no" ] && echo "valid integer" || echo "invalid integer"\`

    it is not worked out for numeric with character inputs from user.

    integer testing
    2w
    int.sh: line 4: declare: 2w: value too great for base (error token is "2w")
    int.sh: line 5: [: =: unary operator expected
    invalid integer

    could you let me know how can resolve this?
    – Vinoth Jun 17 '14 at 07:09