bash 意外标记“then”附近的语法错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36527194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:28:56  来源:igfitidea点击:

syntax error near unexpected token `then'

linuxbash

提问by Jone Jamson

I created a script that helps administrators add and remove users from text file instead of doing it manually. I ran into this error and i'm having trouble solving it.

我创建了一个脚本来帮助管理员从文本文件中添加和删除用户,而不是手动进行。我遇到了这个错误,我无法解决它。

[ec2-user@ip-172-31-15-55 ~]$ ./account-manager user add
./account-manager: line 21: syntax error near unexpected token `then'
./account-manager: line 21: `   then'

How could I fix this error?

我该如何解决这个错误?

#!/bin/bash

file=
action=

if [ -z "$file" ]
then
        echo " Please enter a file with your users"
        exit 0
fi

if [ -z "$action" ]
then
        echo " Please define an account to remove or deleete"
        exit 0
fi

for user in `cat $file`
do
        if[ "$action" == "add" ]
        then
                echo adding user: $user
                useradd $user -m -p password
        fi
        if[ "$action" == "remove" ]
        then
                echo removing user: $user
                userdel -r $user
        fi

done

回答by v7d8dpo4

You should add a space between ifand [in lines 20 and 25. Your code should be like this.

您应该在第 20 和 25 行之间if[中添加一个空格。您的代码应该是这样的。

#!/bin/bash

file=
action=

if [ -z "$file" ]
then
        echo " Please enter a file with your users"
        exit 0
fi

if [ -z "$action" ]
then
        echo " Please define an account to remove or deleete"
        exit 0
fi

for user in `cat $file`
do
        if [ "$action" == "add" ]
        then
                echo adding user: $user
                useradd $user -m -p password
        fi
        if [ "$action" == "remove" ]
        then
                echo removing user: $user
                userdel -r $user
        fi

done

回答by Julian

Pay attention to spacing around your ifstatements, make use of a tool such as http://www.shellcheck.net/to understand where you might have made mistakes.

注意if语句周围的间距,使用诸如http://www.shellcheck.net/之类的工具来了解您可能出错的地方。