Bash脚本语法错误:意外的文件结尾



我试图创建一个简单的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

我不确定我的剧本是不是有错别字,还是其他什么。每当我执行脚本时,我都会收到以下消息

输入数字以选择选项

  1. 添加用户
  2. 删除用户

/createuser.sh:第31行:语法错误:文件意外结束

提前感谢您的帮助!!

错误:

  1. 错误的if/else/fi序列,基本上只有几个错误
if [ ]
then
# something
else
if [ ]
then
# something else
fi
# fi should be here ti close outer if []
  1. 在bash中,if then/elif/elsefi关闭
if []
then
# something
elif []
then
# something else happened
else
# something else than elif happened
fi
  1. ;if []之后,只有当ifthan在同一行时,它才会到达那里,就像这样
if [] ; then
# something
elif []
# something else happened
else
# something else than elif happened
fi
  1. 测试支架[]内的空间
if [ a -eq 5 ]
#   ^       ^
#   +-------+----< notice space here
  1. 在bashwhile中,序列如下while [ ] do done。类似以下内容
while [ i -le 55 ]
do
# do something
done

建议

  1. 在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

相关内容

  • 没有找到相关文章