From 66e08adab8db8f21d8e8d92e41077599083931c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lawrence=20Vel=C3=A1zquez?= Date: Fri, 8 Mar 2024 21:55:30 -0500 Subject: [PATCH] Mentioned that expr uses semi-anchored POSIX BRE; adjusted examples to demonstrate the difference --- SC3015.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/SC3015.md b/SC3015.md index d8a386a..529b9d9 100644 --- a/SC3015.md +++ b/SC3015.md @@ -4,23 +4,21 @@ ```sh #!/bin/sh -[ "$var" =~ .*foo[0-9]* ] +[ "$var" =~ foo[0-9]+ ] ``` ### Correct code: ```sh #!/bin/sh -expr "$var" : ".*foo[0-9]*" > /dev/null +expr "$var" : '.*foo[0-9]\{1,\}' > /dev/null ``` ### 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. - -Use `expr`'s `:` operator instead. +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. ### Exceptions: