I want to check if an input string matches whitelisted file paths, then only I want to perform some operation.

I am doing something like this


[ [ "$path2" =~ "$path1" ] ] && echo "Matches"

Where, if paths are like


These should pass.

Above check is giving me an error

assets/bin/copymain: line 8: [: too many arguments
  • I am all new to regex and bash scripting. I apologise for any silly mistakes. – Ankit Jun 1 at 16:28
  • So you want to check that it contains test not testing? Or do you want to check that the path is exactly one of a hard set list of paths? Where does the input string come from? – Jesse_b Jun 1 at 16:28
  • There would be an array of whitelisted paths, this is just an example. If whitelisted path is mydir/test/**, then mydir/anything should not get passed. Input string would be generated from other function. – Ankit Jun 1 at 16:29
  • AFAIK [ [ and ] ] aren't valid bash syntax: there's [ .. ] and then there's [[ ... ]]. Also, enclosing the RHS argument of =~ in quotes will cause it to be treated as a string not a regex. – steeldriver Jun 1 at 16:47
  • That syntax resembles .gitignore files. That regex version is quite complex to port to bash. Do you need full support for it, or only the '**' scenario? – seshoumara Jun 1 at 16:48

Here path1="mydir/**" uses a globing parameter expansion pattern witch is a totally different language than the RegEx used in the comparison.

[ [ "$path2" =~ "$path1" ] ] && echo "Matches"

But the conditions uses a RegEx:

[[ "$path2" =~ "$path1" ]]

Do not add spaces between the [ [ and ] ] but [[ and ]]

Parameter expansion globing and Regex are two different pattern languages.

If $path1 contains the whitelist pattern, then you must write it in RegEx like this:


[[ ${path2} =~ ${path1} ]] && echo "Matches"

The right side is the RegEx variable path1 and it must not be quoted, or the quotes are interpreted as literal " character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.