Mentioned that expr uses semi-anchored POSIX BRE; adjusted examples to demonstrate the difference

Lawrence Velázquez
2024-03-08 21:55:30 -05:00
parent b63354d214
commit 66e08adab8

@@ -4,23 +4,21 @@
```sh ```sh
#!/bin/sh #!/bin/sh
[ "$var" =~ .*foo[0-9]* ] [ "$var" =~ foo[0-9]+ ]
``` ```
### Correct code: ### Correct code:
```sh ```sh
#!/bin/sh #!/bin/sh
expr "$var" : ".*foo[0-9]*" > /dev/null expr "$var" : '.*foo[0-9]\{1,\}' > /dev/null
``` ```
### Rationale: ### Rationale:
You are using `=~` in a script declared to be compatible with POSIX sh or Dash. 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.
`=~` is [not a POSIX operator](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 instead.
### Exceptions: ### Exceptions: