-2

The task is to display a list of groups from /etc/group that certain user is member of. User name is passed as a parameter. My current code:

#!/bin/bash 
cat /etc/group | grep -w "$1" | cut -d ":" -f1

The problem is that there are certain lines that contain user name but they are not groups that user is member of. Example: syslog:x:106: and adm:x:4:syslog,username. The only thing I want as a result is adm but my current code will also output syslog. Is there a way to correct it?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Mak
  • 91
  • 9

1 Answers1

0

You might be looking for the groups command:

$ groups --help
Usage: groups [OPTION]... [USERNAME]...
Print group memberships for each USERNAME or, ...
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
  • I'm not asking for a command integrated into terminal that would work, but for a solution with my code. However the "groups" does the same output as my code so I guess my implementation is right. Thanks! – Mak Dec 04 '18 at 10:00
  • If you're happy with the output of your code, it can be more simplified into: `awk -F":" -v pat="$1" '$0~pat {print $1}' /etc/group` – User123 Dec 04 '18 at 10:23