Ubuntu下实现用户/组创建及重复检测的Bash脚本需求
完善Ubuntu用户/组创建Bash脚本
原脚本存在的问题
- 用户名检测循环逻辑错误:输入重复用户名后直接
exit 1,无法继续输入新用户名 - 未定义
group变量,缺少组名输入及重复检测逻辑 - 用户名匹配不精确:
egrep "^$username"会误匹配以该用户名开头的其他用户(比如test会匹配test1) - 组创建未实现重复提示逻辑,直接使用
groupadd -f强制创建,不符合需求
修正后的脚本
#!/bin/bash # 检查是否为root用户 if [ $(id -u) -ne 0 ]; then echo "Only root may add a user to the system." exit 2 fi # 输入并验证用户名 read -p "Please enter a username: " username while true; do # 精确匹配/etc/passwd中的用户名(格式:用户名:xxx:...) if grep -q "^$username:" /etc/passwd; then read -p "User $username already exists! Please enter a different username: " username else # 简单验证用户名合法性(符合Linux用户名规则:小写字母、数字、下划线,首字符为字母) if [[ ! "$username" =~ ^[a-z][a-z0-9_]*$ ]]; then echo "Invalid username! Username must start with a lowercase letter, followed by lowercase letters, numbers, or underscores." read -p "Please enter a valid username: " username else break fi fi done # 输入并验证组名 read -p "Please enter a group name: " group while true; do # 精确匹配/etc/group中的组名 if grep -q "^$group:" /etc/group; then read -p "Group $group already exists! Please enter a different group name: " group else # 简单验证组名合法性(规则同用户名) if [[ ! "$group" =~ ^[a-z][a-z0-9_]*$ ]]; then echo "Invalid group name! Group name must start with a lowercase letter, followed by lowercase letters, numbers, or underscores." read -p "Please enter a valid group name: " group else break fi fi done # 创建组和用户 if groupadd "$group"; then if useradd -m -g "$group" "$username"; then echo "User $username and group $group added to system successfully!" exit 0 else echo "Failed to create user $username!" # 清理已创建的组(如果用户创建失败) groupdel "$group" exit 1 fi else echo "Failed to create group $group!" exit 1 fi
脚本说明
- 权限检查:脚本开头先判断是否为root用户,非root直接退出
- 用户名检测:使用
grep -q "^$username:"精确匹配用户名,避免误判;添加了用户名合法性验证,符合Linux系统用户名规则 - 组名检测:和用户名逻辑一致,实现重复检测提示及合法性验证
- 创建逻辑:先创建组,组创建成功后再创建用户;若用户创建失败,自动清理已创建的组,避免残留无效组
- 错误处理:每一步操作都做结果判断,给出明确的错误提示
内容的提问来源于stack exchange,提问作者Robbin Huisman
相关产品推荐
相关产品推荐

