Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do character comparison in bash scripts?

Tags:

bash

shell

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?

like image 654
posixKing Avatar asked Dec 05 '22 16:12

posixKing


1 Answers

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
like image 56
makadev Avatar answered Feb 04 '23 21:02

makadev