I'm writing a script that executes scripts stored in a given directory, based on an array containing the filenames of the scripts.
Here's a section of my 'menu', just to clarify:
#######
Title: Test script 1
Description: Test script 1
To execute: 0
#######
Title: Test script 2
Description: Test script 2
To execute: 1
#######
I have an array named array that contains the names of the scripts with an index corresponding to the printed value under "to execute". Right now, I'm using a case statement to handle input and provide an exit option.
case $REPLY in
[Ee]) clear
exit;;
[[:digit:]] $scriptDirectory/${array[$REPLY]}
However, the [[:digit:]] expression only matches 0-9. I need a regex that works in the case statement that matches 0-999, or similar.
case
only uses globs (aka filename expansion patterns), not regular expressions.
You can set extended glob with shopt -s extglob
, then you can use +()
to match one or more occurrence :
shopt -s extglob
case $REPLY in
[Ee]) clear
exit;;
+([[:digit:]])) $scriptDirectory/${array[$REPLY]};;
esac
Note : I added missing )
after your second case pattern and missing ;;
at the end of the same line. Also added the esac
missing statement.
Update :
If you just want to match numbers between 0 and 999, try this :
[0-9]?([0-9])?([0-9])) $scriptDirectory/${array[$REPLY]};;
Character range are used here as I find it a bit more readable. The result will be the same.
The easiest way I've found is bash is:
^(1000|[0-9]{1,3})$
Using this regex combined with the =~
operator (which interprets the string to the right as an extended regular expression) you can construct a simple test. (with your input as "$1"
)
if [[ $1 =~ ^(1000|[0-9]{1,3})$ ]]; then
echo "0 <= $1 <= 1000 (1)"
else
echo "$1 - invalid number"
fi
Example Use/Output
$ for i in -10 -1 0 1 10 100 999 1000 1001; do ./zero1thousand.sh $i; done
-10 - invalid number
-1 - invalid number
0 <= 0 <= 1000
0 <= 1 <= 1000
0 <= 10 <= 1000
0 <= 100 <= 1000
0 <= 999 <= 1000
0 <= 1000 <= 1000
1001 - invalid number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With