Reputation: 858
I am creating a script that takes a group name, and it should print all the users and the groups they are in including the given one, but I still can't figure out how to do it properly, here is my code:
#!/bin/bash
# contentFile is the file you are trying to read
# contentFile will be a parameter supplied by the user
# thus we leave it empty for now
groupName=
## List of options the program will accept;
## those options that take arguments are followed by a colon
## in this case, group name: n
optstring=n:
## The loop calls getopts until there are no more options on the command line
## Each option is stored in $opt, any option arguments are stored in OPTARG
while getopts $optstring opt
do
case $opt in
n) groupName=$OPTARG ;; ## $OPTARG contains the argument to the option (contentFile in this context)
*) exit 1 ;; ## exit if anything else other than -f file name was entered
esac
done
groups=$(cat /etc/group | cut -d: -f1)
for user in $(cat /etc/passwd | cut -d: -f1)
do
echo grep -q $groupName $groups
if [ $? = 0 ]
then
echo "- grupuri:" "$user" "\n;"
fi
done
Output I am getting
grep -q root adm wheel kmem tty utmp audio disk input kvm lp optical render storage uucp video users sys mem ftp mail log smmsp proc games lock network floppy scanner power systemd-journal rfkill nobody dbus bin daemon http systemd-journal-remote systemd-network systemd-resolve systemd-timesync systemd-coredump uuidd dnsmasq rpc gdm ntp avahi colord cups flatpak geoclue git nm-openconnect nm-openvpn polkitd rtkit usbmux fsociety postgres locate mongodb dhcpcd docker openvpn mysql
expected output:
whoopsie - grupuri:whoopsie;
colord - grupuri:colord;
sssd - grupuri:sssd;
geoclue - grupuri:geoclue;
pulse - grupuri:audio;pulse;pulse-access;
Your help is much appreciated
Upvotes: 1
Views: 1447
Reputation: 44264
Consider the following bash script;
group='certuser'
for user in $(awk -F ':' "/${group}/"'{print $4}' /etc/group | tr ',' '\n'); do
echo "$(groups $user)"
done
Where
awk -F ':' '/certuser/ { print $4 }' /etc/group
Gets each users in the $group ('certuser') group, seperated by a
,
Using awk to remove group info so we're only keeping users
| tr ',' '\n'
Pipes that csv to the for-loop
echo "$(groups $user)"
Use the
groups
command to get all users in that group
Upvotes: 3
Reputation: 242343
Use the getent
command to retrieve information about groups and users. In particular, getent group
queries the groups, while getent passwd
queries the users.
#! /bin/bash
group=$1
gid=$(getent group "$1" | cut -d: -f3)
getent passwd \
| awk -F: -v gid=$gid '($4==gid){print $1}' \
| xargs -n1 groups
Upvotes: 1