coredumped0x
coredumped0x

Reputation: 858

Bash script, for a given group name, print all the users and the groups they are in including the given one

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

Answers (2)

0stone0
0stone0

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

  1. awk -F ':' '/certuser/ { print $4 }' /etc/group

    Gets each users in the $group ('certuser') group, seperated by a ,

    Using to remove group info so we're only keeping users

  2. | tr ',' '\n'

    Pipes that csv to the for-loop

  3. echo "$(groups $user)"

    Use the groups command to get all users in that group

Upvotes: 3

choroba
choroba

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

Related Questions