0

I have list of secondary group names eg group_1 group_2.. group_n and a username eg : user1

Now i need to do

  1. Make sure that all the groups are present

  2. Make sure no extra groups are present

I tried using id -nG user1 | grep <group_1> | grep <group_2> | .. | grep <group_ n> and evaluting the exitcode but that only makes sure that required groups are present.I'm not sure how to verify no extra groups (groups not in my list) are present.

rdm_
  • 67
  • 1
  • 8

1 Answers1

1

You can use a grep like this:

grep -oFf a_file_with_secondary_group_names_per_line

An example code how you can achieve what you want:

#!/bin/bash
user=username
file=file_with_secondary_groups
if [[ $(id -G "$user" |wc -w) == $(id -nG "$user" | grep -coFf "$file") ]]; then
  echo "*All groups are present"
  # i.e the number of group and the number of group matched is the same
  if [[ $(id -G "$user" |wc -w) == $(grep -co '.' "$file") ]]; then
    echo "*No extra groups"
    # i.e the number of groups and the number of groups in the file are same
  else
    echo "-Extra groups present"
  fi
else
  echo "-All groups are not present"
fi
Jahid
  • 21,542
  • 10
  • 90
  • 108
  • Thanks @jahid but how to make sure no extra groups(groups not in my list) are present? – rdm_ May 13 '16 at 12:09
  • Many thanks @jahid i think ` $(id -nG "$user" | grep -coFf "$file") == $(id -G "$user" |wc -w) ` should be enough to make sure only the listed groups are present but some groups consists of spaces eg `admin group` so when we do `wc -w` these will be calculated as 2 separate groups `admin` `group` any help on this would be appreciated and also would it it be possible to pass the list without storing in a file. Thanks. – rdm_ May 14 '16 at 12:57
  • @rdm_ : Do note that I didn't use `-nG`, I used `-G` for that very purpose. And, yes the first condition is enough. – Jahid May 14 '16 at 13:59