语法错误如果[" $ foo"在bash中==" bar"]

时间:2014-11-14 14:23:56

标签: bash

我是bash的新手,但根据我看到的一些流量控制指南,这个脚本应该可以找到,但我得到line 4 syntax error near unexpected token then

#!/bin/bash
echo "Type your name"
read personname
if["$personname" == "kevin"]; then
    echo "Your name is kevin"
    exit 1
fi

2 个答案:

答案 0 :(得分:3)

您在if语句中缺少一些空格

#!/bin/bash
echo "Type your name"
read personname
if [ "$personname" == "kevin" ]; then
    echo "Your name is kevin"
    exit 1
fi

答案 1 :(得分:3)

在shell中,[是一个命令,]是该命令的参数。参数必须是单独的单词,用空格分隔。除此之外,我还建议将==更改为=(后者得到更广泛的支持)。此外,您可以使用echo合并readread -p语句。

#!/bin/bash
read -p $'Type your name\n' personname
if [ "$personname" = "kevin" ]; then
    echo "Your name is kevin"
    exit 1
fi

$'string\n'语法允许您在提示字符串中使用换行符\n等字符。如果您实际上不需要换行符,则只需使用'Type your name: '之类的内容,提示符就会出现在与用户输入相同的行中。