Shell logic: How to create user/group if no user/group with that UID/GID exists
The following bash / shell snippet is an example of how to create a user and group if no user/group with that UID/GID exists yet:
How to create a group if no group with that GID exists
getent group $GID || groupadd --gid $GID $USERNAME
How to create a user if no user with that UID exists
getent passwd $UID || useradd --uid $UID --gid $GID -m $USERNAME
How it works
getent group $GID
will return the group with the given GID if it exists, or nothing if it doesn’t. Example:
$ getent group 1000
myuser:x:1000:
$ echo $?
0
in case no such group exists:
$ getent group 12345
$ echo $?
2
After that, we will use ||
to execute the groupadd
command only if getent
returns a non-zero exit code (i.e., the group doesn’t exist).
groupadd --gid $GID $USERNAME
will create a group with the given GID and name.
How to include that into your script
Ensure to use braces if you are using this command in a &&
chain to avoid unexpected behavior.
Example:
# Create user/group only of no such user/group exists
(getent group $gid || groupadd --gid $gid $USERNAME) \
&& (getent passwd $uid || useradd --uid $uid --gid $gid -m $USERNAME) \
&& echo "Created user & group or used existing ones"
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow