-1

I tried to check my variable value with case statement and regular expression in sh script like the following code:

#!/bin/sh

test="test.1.testing"

case $test in
test.[5-9]+.testing) echo "value type 1";;
test.[1-4]+.testing) echo "value type 2";;
esac

This script doesn't work, have any solution with sh script (not bash)

I changed the symbol "+" by "*" and the script run succesfully, but I need to test with "+" (for 1 or more occurrence)

#!/bin/sh

test="test.1.testing"

case $test in
    test.[5-9]*.testing) echo "value type 1";;
    test.[1-4]*.testing) echo "value type 2";;
esac
codeforester
  • 39,467
  • 16
  • 112
  • 140
developer
  • 4,744
  • 7
  • 40
  • 55

1 Answers1

2

Pattern matching in case is performed according to Pathname Expansion. Special symbols are *, ?, […].

Symbol + is treated as simple character, not a quantifier for [].

The same is true for *; here it's not a regex quantifier for [] but rather a separate pattern symbol. In your case, it matches zero characters which results in successful pattern match. You can check this by removing * from case.

Thus you should use the following code:

#!/bin/sh

test="test.1.testing"

case $test in
    test.[5-9].testing) echo "value type 1";;
    test.[1-4].testing) echo "value type 2";;
esac
Alexey Ivanov
  • 11,541
  • 4
  • 39
  • 68
  • you're right, have you any solution to do it with case statement? – developer May 09 '13 at 10:16
  • 1
    @AhmedZRIBI I edited my answer and added the working code. If you need to match `test.11.testing` too, then I'd suggest using a tool with more sophisticated regular expressions, for example `perl`, `grep`, `sed`. Additionally, if you allow two digits, then what case does `test.15.testing` fall in? If only the first digit is important, add `*` after `]` like you did. Yet such construct would also allow `.1a.` as well as `.15.`; so if you want to ensure there are only digits, you have to use another tool to check the value. – Alexey Ivanov May 09 '13 at 14:50