Added case alternative

Lawrence Velázquez
2024-03-08 23:08:41 -05:00
parent 66e08adab8
commit a67284dc20

@@ -4,21 +4,36 @@
```sh
#!/bin/sh
[ "$var" =~ foo[0-9]+ ]
if [ "$var" =~ foo[0-9]+ ]; then
echo matched
fi
```
### Correct code:
```sh
#!/bin/sh
expr "$var" : '.*foo[0-9]\{1,\}' > /dev/null
if expr "$var" : '.*foo[0-9]\{1,\}' >/dev/null; then
echo matched
fi
```
or
```sh
#!/bin/sh
case $var in
*foo[0-9]*)
echo matched
;;
esac
```
### Rationale:
You are using `=~` in a script declared to be compatible with POSIX sh or Dash, but `=~` is [not specified by POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html) and is unlikely to work outside `[[ ]]` in Bash and Ksh.
Instead, use `expr`'s `:` operator, which is [specified by POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/expr.html#tag_20_42_13_01). It may be necessary to revise the regular expression because `expr` uses [POSIX basic regular expressions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03) anchored to the beginning of the string, as opposed to the unanchored [extended regular expressions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) used by `[[ str =~ re ]]` in Bash and Ksh.
Use [`expr`'s `:` operator](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/expr.html#tag_20_42_13_01) instead. It may be necessary to revise the regular expression because POSIX `expr` uses [basic regular expressions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03) anchored to the beginning of the string, as opposed to the unanchored [extended regular expressions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_04) used by `[[ str =~ re ]]` in Bash and Ksh.
Alternately, use `case` if the matching can be done with [shell patterns](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13) instead of regular expressions. This avoids the need for an external utility.
### Exceptions: