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
}
1

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.