-3

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?

MoBarger
  • 43
  • 3

3 Answers3

1

Bash has direct support for regular expressions.

if ! [[ $mystring ~= $pattern ]]; then
    exit
fi
kojiro
  • 71,091
  • 17
  • 131
  • 188
0

Use Bash's Double-Bracket Regex Tests

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
Todd A. Jacobs
  • 76,463
  • 14
  • 137
  • 188
  • Thank you so much everyone! I think I was being too strict. I ended up using the following as the digit mask can change over time. – MoBarger Jun 06 '13 at 15:03
0

Doable directly in bash

var=AA-1.2.33
[[ $var =~ ^AA-.\..\...$ ]]
echo $?
0
var=AA-1.2.3355
[[ $var =~ ^AA-.\..\...$ ]]
echo $?
1
iruvar
  • 21,786
  • 6
  • 51
  • 81