-1

What is the output difference between these commands?

ps -ef | grep  \[t\]tyS1

and

ps -ef | grep ttyS1

Expected results is that previous will grep for [t]tyS1 but is not actually happening.

gehbiszumeis
  • 2,788
  • 4
  • 19
  • 33
  • [so] is for programming questions, not questions about using or configuring Linux and its applications. [su] or [unix.se] would be better places for questions like this. – Barmar Jan 10 '19 at 08:32
  • 1
    The first one will not match the `grep` command itself, the second one will. Because the string `[t]tyS1` doesn't match the regexp `[t]tyS1`. – Barmar Jan 10 '19 at 08:33
  • See https://unix.stackexchange.com/questions/2062/grep-why-do-brackets-in-grep-pattern-remove-the-grep-process-from-ps-results – Barmar Jan 10 '19 at 08:34
  • [Quoting](https://mywiki.wooledge.org/Quotes). You want to match the string `[t]tyS1` literally, or you want to match `ttyS1` ? – KamilCuk Jan 10 '19 at 08:35
  • Using a regex which doesn't match itself literally is a common trick to avoid having the search find itself in `ps` output. – tripleee Jan 10 '19 at 08:55
  • You have to add the option -E to grep. "Interpret PATTERN as an extended regular expression (ERE, see below)." – sinkmanu Jan 18 '19 at 07:33

1 Answers1

-2

Both commands looks for the same word: ttyS1, because the 'optional letters' that you put enclosed squared braquets contains only 't'. If you want to search for the string: [t]tyS1, you should enclose your regular expression between quotes (" or ') to avoid shell substitutions, but I'm not sure if it is your purpose.

ps -ef | grep  "\[t\]tyS1"

In the case that you want to search for ttyS1 OR ptyS1 the command would be:

ps -ef | grep '[pt]ty'

Hope this helps you.

Sergio.Uma
  • 52
  • 5
  • 1
    No, the backslashes serve the same purpose as quotes, you need to drop them if you add quotes and then the meaning is different. – tripleee Jan 10 '19 at 08:54
  • If you would want to search for the [ itself, for example the process: "[kworker/3:0]", you need to use both quote and back slash – Sergio.Uma Jan 10 '19 at 09:01