lufork lufork - 2 months ago 10
Bash Question

How to do character comparison in bash scripts?

Here is my code

#! /bin/bash
read var
if [ $var="Y" -o $var="y" ]
then
echo "YES"
else
echo "NO"
fi


I want to print YES if the user presses y or Y, otherwise I want to print NO. Why doesn't this code work?

Answer

Basically, your Condition is wrong. Quote your variables and leave spaces between operators (like shellter wrote). So it should look like:

#! /bin/bash
read var
if  [ "$var" = "Y" ] || [ "$var" = "y" ]
then
    echo "YES"
else
    echo "NO"
fi

Edit: for POSIX ccompatibility

  • Replaced == with = - see comments
  • Replaced -o syntax with || syntax - see comments