Shell 逻辑:如何在不存在具有该 UID/GID 的用户/组时创建用户/组
以下 bash/shell 片段是当尚不存在具有该 UID/GID 的用户/组时如何创建用户和组的示例:
如何在不存在具有该 GID 的组时创建组
create_user_group.sh
getent group $GID || groupadd --gid $GID $USERNAME如何在不存在具有该 UID 的用户时创建用户
create_user_if_not_exists.sh
getent passwd $UID || useradd --uid $UID --gid $GID -m $USERNAME工作原理
getent group $GID将返回具有给定 GID 的组(如果存在),如果不存在则什么也不返回。示例:
getent_group_example.sh
$ getent group 1000
myuser:x:1000:
$ echo $?
0如果不存在这样的组:
getent_group_not_found_example.sh
$ getent group 12345
$ echo $?
2之后,我们将使用 || 仅在 getent 返回非零退出代码(即组不存在)时执行 groupadd 命令。
groupadd --gid $GID $USERNAME将创建具有给定 GID 和名称的组。
如何将其包含到你的脚本中
如果你在 && 链中使用此命令,请确保使用大括号以避免意外行为。
示例:
create_user_group_conditional.sh
# 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"Check out similar posts by category:
Linux
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow