Ioannis
Ioannis

Reputation: 25

Bash if else if conditions issue

I am trying some simple bash scripting, and I am working on a simple comparison script, where the program reads a character char, and if it is "Y" or "y", it prints "YES", and if it is "N" or "n", it is "NO". The letters Y, y, N, n are supposedly the only ones that will be used as input.

#!/bin/sh

read char
if (( $char = "Y" )) || (( $char = "y" ))
then
    echo "YES"
else
    echo "NO"
fi

The above script works with Y or y, but when I try to put N or n, it still prints "YES", and I'm trying to figure out what I am doing wrong. I know it's something to do with the parentheses, because when I use a syntax with brackets, like this

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

it works just fine. I have tried all the combinations for the parentheses, like

if (( "$char" = "Y" )) || (( "$char" = "y" ))

or

if (( $char == "Y" )) || (( $char == "y" ))

or

if (( "$char" == "Y"))  ||  (("$char" == "y" ))

or

if (( "$char" == "Y"  ||  "$char" == "y" ))

but none of them work. Can you please tell me what is the mistake I am making?

Upvotes: 1

Views: 103

Answers (1)

chepner
chepner

Reputation: 530920

(( ... )) is for arithmetic only; you are performing string comparison. Use [[ instead. You can use pattern matching to check for either upper- or lowercase at the same time.

if [[ $char = [Yy] ]]; then

If you really want to use /bin/sh for portability, then use two [ commands:

if [ "$char" = Y ] || [ "$char" = y ]; then

Upvotes: 5

Related Questions