Shell – Why two almost idetical grep commands return different output: w/o and with filename

globgrepregular expressionshell

I have 2 almost identical greps:

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

vs.

[AlexL@localhost tmp]$ grep /bin/*sh /etc/passwd    
/etc/passwd:root:x:0:0:root:/root:/bin/bash
/etc/passwd:AlexL:x:500:500::/home/AlexL:/bin/bash
/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

Best Answer

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
Related Question