'Shell script grep command -c (count) -- does command-line ordering matter?

just a quick question regarding a doubt. What's the difference between these two:

grep "$genre" "$i" | grep "$type" -c

and

grep "$genre" "$i" | grep -c "$type"

Do they do perhaps the same thing?



Solution 1:[1]

As you can see from man grep, the -c switch belongs to the so-called "General Output Control". Those switches can be placed on different places in the grep ... command and this has no impact on the general outcome, so indeed, both lines you mention are equal.

Solution 2:[2]

The POSIX standard-mandated behavior for grep "$type" -c, presuming that $type does not expand to a string starting with a dash, is to treat -c as a filename.

Only nonstandard versions of grep (such as the one built by the GNU project and commonly found on Linux systems) will treat -c as an option enabling "count" behavior when it isn't before the first positional argument.

It's bad practice to write your scripts to require nonstandard tools unless they gain some concrete benefit from those tools. Use grep -c "$type".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dominique
Solution 2 Charles Duffy