posixKing
posixKing

Reputation: 418

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?

Upvotes: 4

Views: 37512

Answers (6)

d_k
d_k

Reputation: 25

Try this code.

#! /bin/bash
read var
echo -e "YES\nNO\n" | grep -i $var

Upvotes: 0

ABN
ABN

Reputation: 1152

Below is the code that I tried.

#! /bin/bash
read -p "Are you Sure?(Y/N) " answer
if [ "$answer" = "y" ] || [ "$answer" = "Y" ]; then
  echo "Do your stuff."
else
  echo "Do your other stuff"
fi

Add whitespace around '=' and your code will run fine.

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

Upvotes: 1

Gary Dean
Gary Dean

Reputation: 23

If all you require is a upper/lowercase comparison, use the ,, operator on the variable being compared ( note the ${var,,} ):

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

or more succinctly:

#!/bin/bash
read var
[ ${var,,} = 'y' ] && echo 'YES' || echo 'NO'

or the way I might actually do it:

#!/bin/bash
read var
[[ "${var,,}" == 'y' ]] && echo 'YES' || echo 'NO'

Upvotes: 1

Jorvis
Jorvis

Reputation: 386

There is minor syntax error in your code.

Correction : There should be a white space between operators and variables

read var

if [ $var = "Y" -o $var = "y" ]
then
    echo "YES"
else
    echo "NO"
fi

Try the above bash script.

Hope it would work fine.

Happy Coding!

Upvotes: 1

makadev
makadev

Reputation: 1054

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

Upvotes: 10

SLePort
SLePort

Reputation: 15461

With Bash, you can also use regular expression in your test with the =~ operator:

read var
[[ "$var" =~ [Yy] ]] && echo "YES" || echo "NO"

Or as Benjamin W. mentionned, simply use character range with the == operator:

read var
[[ "$var" == [Yy] ]] && echo "YES" || echo "NO"

Upvotes: 5

Related Questions