1

I am trying to get usernames from /etc/passwd if UID equal/greater than 1000 using a for loop. The below simple bash script works but prints the username twice for some reason.

#!/bin/bash

for userid in `awk -F: '{print $3}' /etc/passwd`
do
if (("$userid" >= 1000)); then
echo "Valid User" :`cat /etc/passwd | grep $userid | awk -F: '{print $1,$3}'`
fi
done
2
  • 2
    Why not just awk -F : '$3 >= "1000" {print "Valid User " $1,$3}' /etc/passwd ? Aug 3, 2019 at 5:35
  • Correction of double quotes around 1000: awk -F : '$3 >= 1000 {print "Valid User " $1,$3}' /etc/passwd Aug 3, 2019 at 6:07

1 Answer 1

4

try this,

 awk -F ':' '$3>=1000 {print "Valid User :"$1","$3}'  /etc/passwd

maybe you might have the user IDs like 1000 and 10001. So your grep leads to duplicate while iterating in for loop.

Try as

 echo "Valid User" :`cat /etc/passwd | grep ":$userid:" | awk -F: '{print $1,$3}'`
5
  • Thanks @msp9011 awk -F ':' '$3>=1000 {print "Valid User :"$1","$3}' /etc/passwd
    – Kumar
    Aug 3, 2019 at 5:41
  • Can you tell me why the "for" loop prints username twice? Just to understand the loops. Thank you,
    – Kumar
    Aug 3, 2019 at 5:47
  • @Kumar as mentioned in the answer , the duplicate happens becos grep is not having boundaries.... if we use grep XX it will get you both XX and XXX. So you should have boundaries to iterate properly like grep "\bXX\b" or with a static string which I used in the answer as grep ":$userid:"
    – Siva
    Aug 3, 2019 at 5:52
  • @msp9011 His comment gives the correct output as yours has a syntax error. By having 3 and not $3 before muru edited it, your answer prints the username and then a comma and the number 3 when he wants it to print the username and the userid. Aug 3, 2019 at 6:09
  • You don't need cat.
    – MaXi32
    Aug 10, 2021 at 18:23

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.