0

I'm new to unix and I've already came across something that happens a lot.

I type a command (for example, ps -eo 'tty,pid,comm') and get back text. As far as I understand, when I pipe the result into grep it should search the output and give me back results from that output.

So why, then, do I get back a result that looks nothing like the command ps? I get back a long text that is not even in the form of the original ps command and consists of obscure information and looks like a setting file.

  • 3
    can you show us a short example? it should work as you understand, so something else is going on. – Jeff Schaller Aug 8 '16 at 13:37
  • I use the command ps -eo 'tty,pid,comm' | grep ?. I get back the following: jameiyolo:HJDSK notes.txt:COYG basically just a bunch of random filenames I've created and the following lines don't make any sense to me (start with set_keybindings.py...). – asaf92 Aug 8 '16 at 14:08
  • 2
    FYI it's easier to read the updates if you can edit your original post – Jeff Schaller Aug 8 '16 at 14:10
3

It appears, based on your comment, that the output you're seeing is the contents of files that have a single character filename that match the name of the first of such files. The reason is that the ? character in your grep command is being expanded by the shell before being executed.

Thus, your ps command is doing what it should, but grep is completely ignoring that input in preference to grepping files on the command-line.

Demonstrate this for yourself by doing something like:

mkdir ~/tempdir
cd ~/tempdir
ps -eo 'tty,pid,comm' | grep ?

which will create an empty directory (no files in it), which will then allow the ? to fail to expand, and pass directly to grep. Then create two files like this:

touch a
echo thisisfilebwithana > b

and then re-run just the grep, like this:

grep ?

and you'll see

thisisfilebwithana

because grep saw this:

grep a b

which it interpreted as "show me all the lines from file b that contain an 'a'".

What you probably want to do instead, is escape the question mark:

ps -eo 'tty,pid,comm' | grep \?

or

ps -eo 'tty,pid,comm' | grep '?'
| improve this answer | |

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.