首页 > 解决方案 > Bash 脚本语法错误:文件意外结束

问题描述

我正在尝试创建一个简单的 bash 脚本来在 ubunutu 上创建和删除用户,这是我的脚本

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 行:语法错误:文件意外结束

预先感谢您的帮助 !!

标签: bashubuntu

解决方案


错误:

  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/else关闭了fi所以像这样的东西
if []
then
   # something
elif []
then
   # something else happened
else
   # something else than elif happened
fi
  1. ;after 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. 用于-s在 bash 中读取密码以在键入时隐藏它。

结论,上面的所有修复都是工作脚本:

#!/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

推荐阅读