0

I wrote a while loop to search inside files and append the output to a text file , but it seems like it's reading only the first line of that text file . How do I fix it ?

while read line
do
x=`echo $line`
y=`grep $x: /etc/group | cut -d ":" -f 3`
grep $y /etc/passwd | cut -d ":" -f 1 >> users
grep $y /etc/group | cut -d ":" -f 4 | tr "," "\n" >> users
done < filename
1
  • what does filename contain? Commented Mar 13, 2014 at 7:01

2 Answers 2

0

Perhaps you need to wrap $x and $y in quotes, as otherwise grep may interpret anything after the first space as the name of the file to be searched:

#!/bin/bash                                                                                                                                    

while read line
do
    x=`echo $line`
    y=`grep "$x:" /etc/group | cut -d ":" -f 3`
    grep "$y" /etc/passwd | cut -d ":" -f 1 >> users
    grep "$y" /etc/group | cut -d ":" -f 4 | tr "," "\n" >> users
done < filename
0

This might be a bit safer as some of the grep statements may pick up the wrong fields (i.e. it does not check for the correct field):

while read GROUP
do
  GROUP_ID=`grep ^$GROUP: /etc/group | cut -d ":" -f 3`

  USER_ENT=`grep -e '\(.*:\)\{3\}'$GROUP_ID':' /etc/passwd`
  [ $? -eq 0 ] && cut -d ":" -f 1 <<<$USER_ENT

  GROUP_ENT=`grep -e '\(.*:\)\{2\}'$GROUP_ID':' /etc/group`
  [ $? -eq 0 ] && cut -d ":" -f 4 <<<$GROUP_ENT | tr "," "\n" | grep -v ^$

done < $FILE_NAME | sort | uniq >users

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.