是的,伙计们,非常感谢你们的帮助我刚修好
我试图创建一个简单的bash脚本来创建和删除ububutu上的用户,这是我的脚本
sudo nano createuser.sh
#!/bin/bash
choice=2
# Main Display
echo "Enter Number to select an option"
echo
echo "1) Add User"
echo "2) Delete User"
echo
while [ $choice -eq 2 ]; do
read choice
if [ $choice -eq 1] ;
then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd $user_name -m -p $user_passwd
cat /etc/passwd
else if [$choise -eq 2] ; then
cat /etc/passwd
echo -e "Enter Password"
read del_passwd
echo -e "User to be deleted:"
read del_user
sudo userdel -r $del_user
cat /etc/passwd
echo
fi
我不确定我的剧本是不是有错别字,还是其他什么。每当我执行脚本时,我都会收到以下消息
输入数字以选择选项
- 添加用户
- 删除用户
/createuser.sh:第31行:语法错误:文件意外结束
提前感谢您的帮助!!
错误:
- 错误的
if/else/fi
序列,基本上只有几个错误
if [ ]
then
# something
else
if [ ]
then
# something else
fi
# fi should be here ti close outer if []
- 在bash中,
if then/elif/else
被fi
关闭
if []
then
# something
elif []
then
# something else happened
else
# something else than elif happened
fi
;
在if []
之后,只有当if
和than
在同一行时,它才会到达那里,就像这样
if [] ; then
# something
elif []
# something else happened
else
# something else than elif happened
fi
- 测试支架
[]
内的空间
if [ a -eq 5 ]
# ^ ^
# +-------+----< notice space here
- 在bash
while
中,序列如下while [ ] do done
。类似以下内容
while [ i -le 55 ]
do
# do something
done
建议
- 在bash中使用
-s
读取密码,以在键入时隐藏密码
结论,上面的所有修复都是工作脚本:
#!/bin/bash
choice=2
# Main Display
echo "Enter Number to select an option"
echo
echo "1) Add User"
echo "2) Delete User"
echo
while [ $choice -eq 2 ]
do
read choice
if [ $choice -eq 1 ]
then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd $user_name -m -p $user_passwd
cat /etc/passwd
elif [ $choise -eq 2 ]
then
cat /etc/passwd
echo -e "Enter Password"
read del_passwd
echo -e "User to be deleted:"
read del_user
sudo userdel -r $del_user
cat /etc/passwd
echo
else
echo "Wrong option you have 1 or 2"
fi
done
这是我现在的工作脚本
#!/bin/bash
choice=2
# Main display echo "Enter number to select an option" echo echo "1) Add User" echo "2) Delete User" echo
while [[ "$choice" -eq 2 ]]; do
read choice
if [[ "$choice" -eq 1 ]] ; then
echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd "$user_name" -m -p "$user_passwd"
cat /etc/passwd else
if [[ "$choice" -eq 2 ]] ; then
cat /etc/passwd
echo
echo -e "User to be deleted:"
read del_user
sudo userdel -r "$del_user"
cat /etc/passwd
echo
choice=2
fi
fi
done