0

I have a problem

If [[ * ]]
then
continue

else
exit 1
fi

I want to test that the argument to my switch (for example -d 3) is a valid positive decimal integer number (a sequence of one or more of any of the ASCII characters from 0 to 9). After -d there can be only be a number [0,infinity). Everything else is bad. I do not know what to put instead of *.

Can you help me ? Argument after -d is at $2 position.

3
  • Can you safely assume that the value will always be a number? What if a user enters letters?
    – terdon
    Nov 21 '13 at 16:42
  • 1
    Are 0x123, 1.23e20, 4+4, 2#1111, 0123, 0888, -0.00, 1.23, .123 acceptable numbers? Nov 21 '13 at 17:23
  • acceptable are only 0,1,2,3,4,5,6,7,8,....infinity. only integer
    – xpukm
    Nov 21 '13 at 18:07
2

From your question and comments, you need $2 to be a non-negative integer:

if [[ "$2" =~ ^[0-9]+$ ]]
then
...

Note also that if is written with a lowercase i.

If your version of Bash doesn't support regular expressions (<3.x), you can use grep to do the heavy lifting for you:

if printf "%s\n" "$2" | grep -qE '^[0-9]+$'
then
...

but see Stephane's comment for a possible caveat of this approach.

32
  • +1 but that of course assumes that $2 is a number.
    – terdon
    Nov 21 '13 at 16:41
  • @terdon You're right, of course. I updated the answer. Thanks :)
    – Joseph R.
    Nov 21 '13 at 16:50
  • 1
    @xpukm JosephR is assuming that you run your script like this: script.sh -d 3 in which case $2 will be whatever you give after -d. How are you testing it?
    – terdon
    Nov 21 '13 at 16:55
  • 2
    Your grep one would say that $'123\nblah' is a valid number. See also expr's : operator. Nov 21 '13 at 17:26
  • 1
    @xpukm I don't know what the problem is. Meanwhile, there are also Stephane's caveats to deal with and you should update your question to tell us which of the number formats Stephane suggests are valid for your use case and which are not.
    – Joseph R.
    Nov 21 '13 at 17:37
1

With any Bourne-like shell (that is, going back as far back as the 70s):

case $2 in
  "" | *[!0-9]*) echo >&2 not OK; exit 1;;
  *) echo OK;;
esac

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.