From: Rasmus Villemoes Date: Tue, 13 May 2025 08:40:23 +0000 (+0200) Subject: cmd: test: add support for =~ operator X-Git-Tag: v2025.10-rc1~91^2~29^2~5 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=04044a567b6b177eb24944343d9e9e61a89edd53;p=thirdparty%2Fu-boot.git cmd: test: add support for =~ operator Currently, the only way to make use of regex matching in the shell is by using "setexpr [g]sub" command. That's rather awkward for asking whether a string matches a regex. At the very least, it requires providing setexpr with a dummy target variable, but also, the return value of setexpr doesn't say whether any substitutions were done, so one would have to do some roundabout thing like env set dummy "${string_to_test}" setexpr sub dummy '' '' if test "${dummy}" != "${string_to_test}" ; then ... When CONFIG_REGEX is set, teach the test command a new operator, =~, which will allow one to more naturally write if test "${string_to_test}" =~ '' ; then ... The =~ operator with similar functionality is also supported in bash when using its "extended" test operator [[ ]]. Reviewed-by: Simon Glass Reviewed-by: Tom Rini Signed-off-by: Rasmus Villemoes --- diff --git a/cmd/test.c b/cmd/test.c index b4c3eabf9f6..a42a523d33d 100644 --- a/cmd/test.c +++ b/cmd/test.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #define OP_INVALID 0 @@ -26,6 +27,7 @@ #define OP_INT_GT 14 #define OP_INT_GE 15 #define OP_FILE_EXISTS 16 +#define OP_REGEX 17 const struct { int arg; @@ -49,6 +51,9 @@ const struct { {0, "-z", OP_STR_EMPTY, 2}, {0, "-n", OP_STR_NEMPTY, 2}, {0, "-e", OP_FILE_EXISTS, 4}, +#ifdef CONFIG_REGEX + {1, "=~", OP_REGEX, 3}, +#endif }; static int do_test(struct cmd_tbl *cmdtp, int flag, int argc, @@ -141,6 +146,20 @@ static int do_test(struct cmd_tbl *cmdtp, int flag, int argc, case OP_FILE_EXISTS: expr = file_exists(ap[1], ap[2], ap[3], FS_TYPE_ANY); break; +#ifdef CONFIG_REGEX + case OP_REGEX: { + struct slre slre; + + if (slre_compile(&slre, ap[2]) == 0) { + printf("Error compiling regex: %s\n", slre.err_str); + expr = 0; + break; + } + + expr = slre_match(&slre, ap[0], strlen(ap[0]), NULL); + break; + } +#endif } switch (op) {