Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a group exists and add if it doesn't in Linux Shell Script

this is a summary of what i want my code to do:

if (group exists) then    (add user to group)  else    (create group)    (add user to group)  fi 

I am using the Ubuntu virtual machine but all of the results i have found on similar sites do not work.

like image 962
annieapple2000 Avatar asked Mar 16 '15 09:03

annieapple2000


People also ask

How do I find the group GID in Linux?

Type the command "id -G " to list all the GIDs for a particular user. Replace " " with the user's Unix or Linux username.

What is the command to check groups in Linux?

Use the most commonly used “cat” command to get the list of the groups available in the “/etc/group” file. When you run the command, you will get the list of the groups.

How do I list all groups in Linux?

We can use the getent command to read the group database to get all groups: $ getent group root:x:0:root bin:x:1:root,bin,daemon daemon:x:2:root,bin,daemon sys:x:3:root,bin adm:x:4:root,daemon tty:x:5: disk:x:6:root lp:x:7:cups,daemon,kent mem:x:8: ...

How do you check if a group exist in Linux?

To view all groups present on the system simply open the /etc/group file. Each line in this file represents information for one group. Another option is to use the getent command which displays entries from databases configured in /etc/nsswitch.


1 Answers

The grep statement in the solution of rups has some flaws:

E.g. grepping for a group admin may return true ("group exists") when there is a group lpadmin.

Either fix the grep-query

grep -q -E "^admin:" /etc/group 

or use

if [ $(getent group admin) ]; then   echo "group exists." else   echo "group does not exist." fi 
like image 168
andiba Avatar answered Sep 21 '22 18:09

andiba