Search code examples
bashdesign-patternsglob

File globbing and matching numbers only


In a bash script I need to verify that the user inputs actual numbers so I have thought the easiest way to make myself sure about that is implementing a case:

case $1 in
    [0-9]*)
    echo "It's ok"
    ;;
    *)
    echo "Ain't good!"
    exit 1
    ;;
esac 

But I'm having hard time with file globbing because I can't find a way to demand the $1 value has to be numeric only. Or another way could be excluding all the alternatives:

case $1 in
    -*)
    echo "Can't be negative"
    exit 1
    ;;
    +*)
    echo "Must be unsigned"
    exit 1
    ;;
    *[a-zA-z]*)
    echo "Can't contain letters"
    exit 1
    ;;
esac

The thing is in this case I should be able to block "special" chars like ! ? ^ = ( ) and so forth... I don't know how to acheive it. Please anyone give me a hint?


Solution

  • If you find a non-numeric character anywhere in the string, the input is bad, otherwise it's good:

    case "$1" in
      *[^0-9]*) echo "first parameter must contain numbers only"; exit 1;;
    esac