1

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?

2
  • 3
    sh is not bash Commented Apr 22, 2017 at 21:18
  • You are right. Should I change it in the original post or not? Commented Apr 23, 2017 at 20:26

1 Answer 1

5

(( ... )) 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.