Hi,

i have to write/as homework/ a script that shows list of all users ,users belong to group (which is main group for every user has been showed) defined as parameter of script. In the case of -c, show count of those users. TIP: /etc/passwd, /etc/group

Dani AI

Generated

Short summary and practical fix.

The reliable way is: look up the group's GID, then list passwd entries whose primary GID equals that value. That works whether accounts come from /etc files or from NSS (LDAP/NIS). Since reported “permission denied” and suggested checking permissions, first confirm file access and whether the system uses a name service.

Check for obvious permission or ACL/SELinux issues:

  • Run ls -l /etc/passwd /etc/group and getent group somegroup.
  • If /etc/group is not world-readable or getent returns nothing, the admin may have restricted access — contact them. getent is preferable when available because it uses the system name service rather than reading files directly.

A compact, portable script that lists users whose primary group is the given group (and supports -c to print a count):

#!/bin/sh
# usage: list_by_group.sh groupname [-c]

if [ -z "$1" ]; then
  echo "Usage: $0 groupname [-c]" >&2
  exit 2
fi

group="$1"
count_flag=0
[ "$2" = "-c" ] && count_flag=1

gid=$(getent group "$group" | awk -F: '{print $3}')
if [ -z "$gid" ] && [ -r /etc/group ]; then
  gid=$(awk -F: -v g="$group" '$1==g{print $3}' /etc/group)
fi
[ -z "$gid" ] && { echo "Group '$group' not found" >&2; exit 1; }

users=$(getent passwd | awk -F: -v G="$gid" '($4==G){print $1}')
if [ $count_flag -eq 1 ]; then
  echo "$users" | grep -cve '^$'
else
  printf "%s\n" $users
fi

Notes and options: to restrict output to human accounts, filter by UID (commonly UID >= 1000) in the awk expression. If both getent and reading /etc/* fail, the restriction is intentional — escalate to the system administrator. This approach avoids brittle greps and works cleanly with multi-source user databases.

Recommended Answers

All 4 Replies

hi,

good for you ! it's in deed a good exercise.

what have tried so far ?

hi,

want to use it with /etc/group but "permission denied" ..its a school linux server ...do u think u should use command getent? i am really newbie in this..

if [ "$2" = "-c" ]; then
   for i in $( grep -i "$1" $SUBOR); do
     let "pocet+=1"
   done
   echo $pocet

else
   for i in $( grep -i "$1" $SUBOR | cut -d ":" -f 1 $SUBOR); do
      echo $i
   done
fi

but still permission denied..i cannot check the result...

everybody should be able to read /etc/group :(
what version of linux is this?
what does print ls -l /etc/{passwd,group}?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.