I wrote the following command in order to match $a with $b, but when the value includes "-", then I get an error. How can I avoid that?

# a="-Xmx5324m"
# b="-Xmx5324m"
#  echo "$a"  | grep -Fxc "$b"
grep: conflicting matchers specified
  • 3
    Consider changing your command to grep -Fxc -- "$b" <<< "$a" to avoid the unnecessary pipe – h3rrmiller Aug 28 '17 at 17:44
  • 8
    By the way, do you really want a regex match, or do you just want to test whether a string is equal to (or is a substring of) another string? In that case, the shell built-ins [[ ... ]] or case would be a better choice, since you avoid both the idiosyncrasies of echo and the child processes. – Uwe Aug 28 '17 at 18:36
  • whether a string is equal this is my test – yael Aug 28 '17 at 19:28
  • 2
  • Another alternative that you shouldn't use that nobody listed : it's possible to escape the dash inside a quoted string so it is understood by grep as a literal character rather than the start of an option, i.e. echo test-test | grep "\-test" will match rather than complain about an unknown -t flag. – Aaron Aug 29 '17 at 12:21

Place -- before your pattern:

echo "$a"  | grep -Fxc -- "$b"

-- specifies end of command options for many commands/shell built-ins, after which the remaining arguments are treated as positional arguments.


Besides of @sebasth's great answer, you could tell that PATTERN with grep's -e option to use PATTERN as a pattern (here using the <<< zsh here-string operator instead of echo; see also printf '%s\n' "$a" for portability).

grep -Fxc -e "$b" <<<"$a"

Or all beside of other options.

grep -Fxce "$b" <<<"$a"

Since your goal is byte-to-byte string equality comparison use the [ command instead.

if [ "$a" = "$b" ]

Or if $a contains $b, using the [[...]] ksh construct:

if [[ $a == *"$b"* ]]

Or more portably in all Bourne-like shells:

case $a in
  *"$b"*) ...

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.