Sample Header Ad - 728x90

Matching numbers with regex in case statement

4 votes
4 answers
24220 views
I want to check whether an argument to a shell script is a whole number (i.e., a non-negative integer: 0, 1, 2, 3, …, 17, …, 42, …, etc, but not 3.1416 or −5) expressed in decimal (so nothing like 0x11 or 0x2A).  How can I write a case statement using regex as condition (to match numbers)? I tried a few different ways I came up with (e.g., [0-9]+ or ^[0-9][0-9]*$); none of them works. Like in the following example, valid numbers are falling through the numeric regex that's intended to catch them and are matching the * wildcard. i=1 let arg_n=$#+1 while (( $i < $arg_n )); do case ${!i} in [0-9]+) n=${!i} ;; *) echo 'Invalid argument!' ;; esac let i=$i+1 done Output:
$ ./cmd.sh 64
Invalid argument!
Asked by siery (221 rep)
Mar 21, 2018, 07:21 PM
Last activity: Jun 22, 2024, 02:54 AM