bash中的IF条件

时间:2015-04-09 03:29:45

标签: bash

我刚开始学习编写bash脚本。这是我想写的简化形式。 问题是尽管输入,它只打印"是"。

#! /usr/bin/bash
read input

if (("$input"== "y" || "$input" == "Y"))
then
   echo "YES";    
elif (("$input" == "n" || "$input" == "N"))
then
     echo "NO";
else
    echo "Not a valid input!!"
fi

2 个答案:

答案 0 :(得分:2)

使用[[代替((

if [[ "$input" == "y" || "$input" == "Y" ]]

并且==运算符之前必须存在空格。

input="n"
if [[ "$input" == "y" || "$input" == "Y" ]]
then
   echo "YES";    
elif [[ "$input" == "n" || "$input" == "N" ]]
then
     echo "NO";
else
    echo "Not a valid input!!"
fi

您也可以使用正则表达式进行条件检查。

if [[ "$input" =~ ^[yY]$ ]]
then
   echo "YES";    
elif [[ "$input" =~ ^[nN]$ ]]
then
     echo "NO";
else
    echo "Not a valid input!!"
fi

答案 1 :(得分:0)

当您自动将输入转换为小写(使用排版)时,您不必费心使用大写字母。
当你使用elif时,总是认为10秒是另一种解决方案。在这种情况下,您可能希望在shell中使用"开关",作为case语句编写:

#!/usr/bin/bash
typeset -l input
read input
case ${input} in 
   "y") echo "Yes";;
   "n") echo "NO";;
   *)   echo "Not a valid input!!";;
esac