Showing results for 
Search instead for 
Do you mean 

script question

SOLVED
Go to Solution
Super Advisor

script question

Hello ,
i have 2 files called users and /etc/passwd.
I need to grep the users from /etc/passwd .
I'm using the below script ,...what is wrong.please advice
for i in $users ; do
>grep $i /etc/passwd >/tmp/users1
>done

Thanks much
Learning ...
6 REPLIES
Trusted Contributor Trusted Contributor

Re: script question

Navin,

You need a small modification in your script

for i in `cat users` ; do
grep $i /etc/passwd >> /tmp/users1
done


"cat users " I assume that the file is users and it has one field per record with the UID

">>" You need to put double redirect. otherwise you will only have the last successful record in the users1 file.
>> means add at the end where > means clear and add in this file.

good luck
Trusted Contributor Trusted Contributor

Re: script question

Note : Please dont forget to assign points.
Thank you
Honored Contributor Honored Contributor

Re: script question

Or sans cat:

for i in $(grep $i /etc/passwd >/tmp/users1
done


Rgds...Geoff
Proverbs 3:5,6 Trust in the Lord with all your heart and lean not on your own understanding; in all your ways acknowledge him, and he will make all your paths straight.
Honored Contributor Honored Contributor

Re: script question

To print all users that have an entry in the "users file" and a corresponding entry in the /etc/passwd file use the following:

# grep -f /etc/passwd
Highlighted
Trusted Contributor Trusted Contributor

Re: script question

Sandman,

I like your oneline script.
very simple... =)
Honored Contributor Honored Contributor

Re: script question

The problem with the ways mentioned is that they will look for ALL occurrences of whatever is in the users file.

Say you have a file like:

tom
dick
harry

When you grep as the folks have done above you could get the users:

tom
tomsmit
dick
dickjr
harry
harry2

It would also be possible to gets matches in other areas of each line, like the home directory or GECOS field.

If you want to look for specific user names only you could do:

for i in $( grep ^${i}: /etc/passwd >/tmp/users1
done

The '^${i}:' will look for ${i} ONLY at the beginning of each line with a ':' after it. So it would show only:

tom:*:UID:GID:GECOS:homedir:shell
dick:*:UID:GID:GECOS:homedir:shell
harry:*:UID:GID:GECOS:homedir:shell