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.
Type the command "id -G " to list all the GIDs for a particular user. Replace " " with the user's Unix or Linux username.
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.
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: ...
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With