在Bash脚本中比较字符串时未找到命令错误(stderr)

时间:2014-12-01 06:02:05

标签: linux bash shell scripting

问题是从用户读取一个字符(可能是'Y', 'y', 'N', 'n')。如果字符为Yy则显示YES。如果字符为Nn则显示NO

Original Problem

这是我的代码:

read option
if ["$option"=="y"] || ["$option"=="Y"]
then
    echo "YES"
else
    echo "NO"
fi

抛出错误 (stderr)

solution.sh: line 2: [Y=y]: command not found
solution.sh: line 2: [Y=Y]: command not found

3 个答案:

答案 0 :(得分:3)

read option
if [ "$option" == "y" ] || [ "$option" == "Y" ]
then
echo "YES"
elif [ "$option" == "n" ] || [ "$option" == "N" ]   
then
echo "NO"
else
echo "?"
fi

答案 1 :(得分:2)

在if ]之前和[之后留出空格。if [ "$option"="y" ] || [ "$option"="Y" ]

答案 2 :(得分:2)

你可以在BASH中使用它:

[[ "$option" == [Yy] ]] && echo "YES" || echo "NO"