Getting all users from a Ubuntu system and loop over it

I followed this article to get the list of the users – https://linuxize.com/post/how-to-list-users-in-linux/

It helped me partially as I found some issues when running it using a root account and putting it inside a shell script. I’m refering to the last part of the script that uses the getent command.

eval getent passwd {$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)..$(awk '/^UID_MAX/ {print $2}' /etc/login.defs)}

this part didnt work as I wanted.. but gives me good intel… the real users in linux system uses the UID defined in the /etc/login.defs which brings the values 1000 through 60000. Knowing that I can get the users by adapting a little bit the script proposed in the article instead of doing:

eval getent passwd {$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)..$(awk '/^UID_MAX/ {print $2}' /etc/login.defs)}

We do:

getent passwd | while IFS=: read -r name password uid gid gecos home shell
   do
     if [ $uid -ge 1000 -a $uid -le 60000 ]
     then
       echo "$name"
     fi
done

You can echo any of those variables there – name, password, uid, gid, gecos, home and shell.
And if you want to loop over the users simply get the system users to a file and read line by line

input = "/tmp/system_users.txt"

getent passwd | while IFS=: read -r name password uid gid gecos home shell
   do
     if [ $uid -ge 1000 -a $uid -le 60000 ]
     then
       echo "$name" >> /tmp/system_users.txt
     fi
done

if [ -f "$input" ]
then
  while IFS= read -r line
  do
    echo "DO SOMETHING""
  done < "$input"
fi

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *