如何为Linux用户管理Bash脚本添加选择管理菜单
为批量用户管理脚本添加交互式菜单
下面是添加了交互式菜单的完整脚本,你可以直接使用:
#!/bin/bash # Function to create users create_users() { echo "Enter the full path of the user file:" read user_file # Check if the file exists if [ -f "$user_file" ]; then while IFS=, read -r username full_name password main_group work_dir; do # Create the user sudo useradd -m -p "$password" -g "$main_group" -d "$work_dir" "$username" # Create the user's personal directories sudo mkdir -p "$work_dir/documents" "$work_dir/images" "$work_dir/videos" "$work_dir/music" # Set appropriate permissions for the personal directories sudo chown -R "$username:$main_group" "$work_dir/documents" "$work_dir/images" "$work_dir/videos" "$work_dir/music" sudo chmod 700 "$work_dir/documents" "$work_dir/images" "$work_dir/videos" "$work_dir/music" done < "$user_file" echo "Users have been created successfully." else echo "The user file does not exist." fi } # Function to delete users delete_users() { echo "Enter the full path of the user file:" read user_file # Check if the file exists if [ -f "$user_file" ]; then while IFS=, read -r username _ _ _ _; do # Delete the user sudo userdel -r "$username" done < "$user_file" echo "Users have been deleted successfully." else echo "The user file does not exist." fi } # Interactive main menu show_menu() { clear echo "=====================================" echo "批量用户管理工具" echo "=====================================" echo "1. 批量创建用户" echo "2. 批量删除用户" echo "3. 退出" echo "=====================================" read -p "请输入选项编号(1-3): " choice } # Main execution loop while true; do show_menu case $choice in 1) create_users read -p "操作完成,按任意键返回菜单..." ;; 2) delete_users read -p "操作完成,按任意键返回菜单..." ;; 3) echo "退出工具,再见!" exit 0 ;; *) echo "无效选项,请输入1-3之间的数字" read -p "按任意键返回菜单..." ;; esac done
关键修改说明
- 新增菜单函数
show_menu:负责清屏并显示交互式选项列表,提示用户输入选择。 - 主循环逻辑:用
while true实现菜单的循环显示,直到用户选择退出(选项3)。 - 选项分支处理:通过
case语句匹配用户输入的选项,分别调用对应的create_users或delete_users函数,同时处理无效输入的提示。 - 优化原函数细节:
- 创建目录时改用
mkdir -p,避免目录已存在时报错 - 修改
chown为chown -R,递归设置权限更稳妥 - 合并重复的权限设置命令,让代码更简洁
- 创建目录时改用
使用注意事项
- 运行脚本需要sudo权限,因为用户创建/删除操作属于系统级操作
- 用户文件必须是逗号分隔的格式,每行对应一个用户信息,格式为:
username,full_name,password,main_group,work_dir - 操作完成后会提示按任意键返回主菜单,方便连续执行多项任务
内容的提问来源于stack exchange,提问作者scifimonk
相关产品推荐
相关产品推荐

