2

I can't seem to allow single integer input only. If someone puts abc, it will work.

But if someone puts in abc123 or 123abc it will still treat it as a valid integer

# input to be an integer.
validate_integer(){

    if [ !  "$#" -eq "1" ]; then
            error "Please enter one numberic value only"
            return 1
    elif [[ "$1" =~ ^[[:alpha:]]+$ ]]; then
            error "Input must be a NUMBER"
            return 1
    else
            return 0
    fi
}
janos
  • 120,954
  • 29
  • 226
  • 236

1 Answers1

2

Change this line:

elif [[ "$1" =~ ^[[:alpha:]]+$ ]]; then

to this:

elif ! [[ "$1" =~ ^[[:digit:]]+$ ]]; then

There, ^[[:digit:]]+$ means the string must be composed of digits from beginning to end, and it must be 1 or more characters long. We negate this with !, to handle the case when the string does not satisfy this condition (not fully numeric).

janos
  • 120,954
  • 29
  • 226
  • 236