I need to ensure a variable passed to my shell script matches a certain pattern. var x has to be in the form of AA-X.X.XX (ie AA-1.2.33). If it doesn't match I need to exit.
Any ideas?
Bash has direct support for regular expressions.
if ! [[ $mystring ~= $pattern ]]; then
exit
fi
See Conditional Constructs in the GNU Bash Manual for a complete explanation of the =~
binary operator. As an example:
good_string='AA-1.2.33'
bad_string='BB.11.222.333'
regex='^AA-[[:digit:]]\.[[:digit:]]\.[[:digit:]][[:digit:]]$'
[[ "$good_string" =~ $regex ]]
echo $? # 0
[[ "$bad_string" =~ $regex ]]
echo $? # 1
Doable directly in bash
var=AA-1.2.33
[[ $var =~ ^AA-.\..\...$ ]]
echo $?
0
var=AA-1.2.3355
[[ $var =~ ^AA-.\..\...$ ]]
echo $?
1