Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active June 27, 2024 22:13
Show Gist options
  • Save fabiolimace/79f0494684bd2902f7366755337e9712 to your computer and use it in GitHub Desktop.
Save fabiolimace/79f0494684bd2902f7366755337e9712 to your computer and use it in GitHub Desktop.
REGEX match for `if` in shells such as Dash (default /bin/sh in Ubuntu)
# using expr
expr_match() {
local text="${1}";
local rexp="${2}";
# NOTE: expr regex is ancored with '^'
expr "${text}" : "${rexp}" > /dev/null;
}
# using grep
grep_match() {
local text="${1}";
local rexp="${2}";
echo "${text}" | grep -E -q "${rexp}";
}
if expr_match "string" "s"; then
echo "true"
fi;
@fabiolimace
Copy link
Author

fabiolimace commented Jun 27, 2024

BUG in GNU's expr:

$ expr "+" : ".*"
expr: erro de sintaxe: argumento inesperado “.*
$ expr match "+" ".*"
expr: erro de sintaxe: faltam argumentos após “.*

The problem doesn't occur in Busybox's expr.

$ busybox expr "+" : ".*"
1
$ busybox expr match "+" ".*"
1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment