Bash:意外令牌'else'附近的语法错误

时间:2013-03-16 18:49:45

标签: bash

我收到以下错误:

./adduser.sh: line 21: syntax error near unexpected token `else'
./adduser.sh: line 21: `        else'

我被困在这里一个小时,我无法理解。

#!/bin/bash
#==========================================================================================================================================
# Script Name:  adduser.sh
# By:           Tim mayo
# Date:         3/2013
# Purpose:      Add a user to the Linux system
# Command line: adduser.sh
#
#==========================================================================================================================================
        read -p "Enter username : " username
        read -s -p "Enter password : " password
        egrep "^$username" /etc/passwd >/dev/null
        if [ $? -eq 0 ]; then
                echo "$username exists!"
                exit 1
        else
                pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
                useradd -m -p $pass $username
                [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
        fi
                else
                        echo "Root user can only add a user to the Linux system"
                        exit 2
fi

2 个答案:

答案 0 :(得分:1)

else关键字与任何if语句无关;您在第20行使用if关键字结束了fi语句。也许您在两个if语句之前错过了read

答案 1 :(得分:0)

另一个“仅以root身份运行”示例:

   #!/bin/bash


if [ $UID -eq "0" ]
then
        read -p "Enter username : " username
        read -s -p "Enter password : " password
        egrep "^$username" /etc/passwd >/dev/null
        if [ $? -eq 0 ]; then
                echo "$username exists!"
                exit 1
        else
                pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
                useradd -m -p $pass $username
                [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
        fi
                 else
                        echo "Root user can only add a user to the Linux system"
                        exit 2
fi
相关问题