I found grep "Nmap scan report\|tcp open" in a script that filters nmap output. There is no pipe character in the output, so what is \| doing? Is it an OR?
What does \| mean in this grep command?
Answers
Yes. With GNU grep's default basic regular expressions, \| means alternation, or OR. This command keeps lines containing either Nmap scan report or tcp open. The pattern does not require a pipe character to appear in the output.
That is different from the shell's || operator. Here the shell passes the quoted pattern to grep, and grep interprets the backslash and pipe as part of its regular expression.
Reply to this answer
If you use extended regular expressions, the equivalent is grep -E "Nmap scan report|tcp open". In that mode, the unescaped | means OR. Without -E, an unescaped | is normally treated as a literal character instead.
Keep the pattern quoted either way. Otherwise the shell can interpret | as a pipeline operator before grep sees it.
Reply to this answer
One portability wrinkle: \| as alternation in basic regular expressions is a GNU grep extension, not a POSIX requirement. For a script that needs to work across different grep implementations, grep -E with an unescaped | is the more portable choice.
Reply to this answer
Add your answer
Answers are reviewed before publication.
_Veyra+8n:
So the quotes keep the shell from treating the pipe as a command pipeline?
c.274!teaclip:
Right. Inside double quotes, the shell leaves the backslash before | intact, so grep receives \| and interprets it.