I have 2 almost identical greps:

[Alex@localhost tmp]$ grep /bin/bash /etc/passwd 
user1:x:501:501:user1 12345:/home/user1:/bin/bash


[AlexL@localhost tmp]$ grep /bin/*sh /etc/passwd    
/etc/passwd:user1:x:501:501:user1 12345:/home/user1:/bin/bash

In 2nd query I got filename prefix for every line match. I know that to get the same result I need to put -h option in 2nd grep, but my question is:

Why do they return different output? Should I add something more?

The task consist of retrieving from /etc/passwd real users (w/o daemons and system users).

Used: CentOS 6.4, grep gnu 2.6.3 version


Your shell expands /bin/*sh. So, what you are really doing is

grep /bin/bash /bin/dash /bin/rbash /bin/rzsh /bin/sh /bin/zsh /etc/passwd

That is, search for the string /bin/bash in the files /bin/dash, /bin/rbash, /bin/rzsh, /bin/sh, /bin/zsh and /etc/passwd.

(Compare with the output of echo /bin/*sh /etc/passwd.)

Since there are several files to search in, grep reports which one it found the string in.

What you want is to quote your search term, so it isn't expanded by the shell, and to use a proper regular expression:

grep '/bin/.*sh' /etc/passwd
  • Thanks, it works! before this I've tried '/bin/*sh' - doesn't work. I forgot a little but RegExps.. forgot to add dot (any char) .* (once, none or many). – ALZ Nov 23 '13 at 17:09

Approximately, for what you need, you can use (-v):

➜  TestZone  sudo grep -v nologin /etc/passwd
mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/bash

Grep was originally developed for the Unix operating system, but is available today for all Unix-like systems. Its name comes from the ed command g/re/p (globally search a regular expression and print), which has the same effect: doing a global search with the regular expression and printing all matching lines.

Source: wiki/Grep

  • -v nologin gives me some other system users like sync, halt, but i need real, human users – ALZ Nov 24 '13 at 8:21

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.