-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
  • 74,557
  • 19
  • 143
  • 201
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
  • 81,402
  • 15
  • 141
  • 199
  • 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
  • 22,736
  • 7
  • 53
  • 82