Home > Enterprise >  Shell script grep command -c (count) -- does command-line ordering matter?
Shell script grep command -c (count) -- does command-line ordering matter?

Time:05-02

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?

CodePudding user response:

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".

CodePudding user response:

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.

  • Related