【发布时间】:2018-05-31 02:07:51
【问题描述】:
我正在编写一个 bash 脚本来添加编辑和删除用户。我无法让它工作。谁能看到我哪里出错了?我已通过创建用 .sh 保存的空文档将 .sh 文件添加到指定文件夹中。当我输入选项 1 或 2 时,它只是要求我再次输入一个选项,而选项 3 显示为 ERROR。 这是我的升级代码 问题是我仍然无法创建文件
主菜单代码
#!/bin/bash
trap ''2
title="////////////////////
10101010101010101010
///main user menu///
10101010101010101010
////////////////////
"
clear
echo "$title"
PS3='Select option: '
choice=("Create User" "Edit User" "Remove User" "Exit")
select cho in "${choice[@]}"
do
case $cho in
"Create User")
/home/hiphappy1/Documents/Courseworkfiles/Users.sh
;;
"Edit User")
/home/hiphappy1/Documents/Courseworkfiles/EditUser.sh
;;
"Remove User")
/home/hiphappy1/Documents/Courseworkfiles/RemoveUser.sh
;;
"Exit")
exit 0
;;
*) echo "ERROR try again"
;;
esac
done
添加用户代码
#!/bin/bash
title="////////////////////////
101010101010101010101010
//Create Multiple Users//
101010101010101010101010
////////////////////////
"
clear
echo "$title"
password="ArsenalRule"
for USERNAME in $(cat /home/hiphappy1/Documents/Courseworkfiles/Userlist.txt)
do
useradd $USERNAME -m –s /bin/bash
echo -e "${password}\n${password}"! | passwd $USERNAME
done
read -r -p "Return to menu? [Y/N] " response
case $response in
[yY])
/home/hiphappy1/Documents/Courseworkfiles/Menulist.sh
;;
[nN])
exit 0
;;
*)
echo "ERROR try again"
;;
esac
exit
编辑用户代码
#!/bin/bash
title2="//////////////////
10101010101010101010
/////Edit User//////
10101010101010101010
////////////////////
"
clear
echo "$title2"
echo "Enter username:"
read username
echo""
id $username &> /dev/null
if [ $? -eq 0 ]; then
echo "$username exists... changing Password."
else
echo "$username does not exist! Password was not changed for $username"
exit 0
fi
passwd $username
read -r -p "Return to menu? [Y/N] " response
case $response in
[yY])
/home/hiphappy1/Documents/Courseworkfiles/Menulist.sh
;;
[nN])
exit 0
;;
*)
echo "ERROR try again"
;;
esac
exit 0
删除用户代码
#!/bin/bash
title="///////////////////
10101010101010101010
////Remove User/////
10101010101010101010
////////////////////
"
clear
echo "$title"
echo -e "Users: "
cat /etc/passwd | grep “[1][0-9][0-9][0-9]” | cut -d “:” -f1
echo ""
echo -e "Select user to remove: "
read username
sudo deluser --remove-home $username
echo ""
echo " Removing"
sleep 2
echo ""
echo " $username REMOVED"
read -r -p "Return to menu? [Y/N] " response
case $response in
[yY])
/home/hiphappy1/Documents/CourseworkFiles/Menulist.sh
;;
[nN])
exit 0
;;
*)
echo "ERROR try again"
;;
esac
【问题讨论】:
-
您的主菜单代码
choice=("Create User" "Edit User" "Remove User" "Exit")但您的案例语句正在寻找“删除用户”。 -
能否把每个文件的内容也说清楚?例如您的菜单执行
/home/hiphappy1/Documents/Courseworkfiles/Users.sh以“创建用户”,但您的创建用户代码似乎读取了自己...?for USERNAME in $(cat /home/hiphappy1/Documents/Courseworkfiles/Users.sh)确保使用小写变量作为局部变量,尤其是当 bash 使用 USERNAME 变量作为环境变量时 -
确保您的双引号实际上是双引号 (
"),而不是 Window 的双引号 (“”)。 -
“删除用户代码”中 grep 中的正则表达式缺少
[。见"get all users whose gid is greater than or equals 1000" -
感谢您的帮助。没有注意到我写的是删除而不是删除。好地方。而缺失的 [.最小的东西似乎是看不见的。我现在设法将菜单连接到方法。但我仍在努力添加用户。它只是说返回菜单 Y/N。