Why is my shell script giving the same output for every case?
Brackets do not work like parenthesis in test
expressions. Also, test
uses =
, not ==
. And you also need to split to expressions properly into tokens (by adding spaces around the =
signs). So what you want, rather, is this:
if [ "$CHAR" = Y -o "$CHAR" = y ]; then echo "YES"elif [ "$CHAR" = N -o "$CHAR" = n ]; then echo "NO"fi
Notice that I've also quoted "$CHAR"
. This makes the program more robust in the cases where $CHAR
is empty or contains spaces. The Y
and N
, on the other hand, do not need any quoting as they are constants and contain no whitespace.
To be more precise, what happens in your program as that each of the $CHAR
expressions expand to a single token that looks something like [N==Y]
, which is a token without special significance for test
. Any token that lacks special significance is interpreted by test
as a "true".
You need to use single =
for string comparison and you've too many brackets. So the code becomes:
#!/bin/bashread CHARif [ "$CHAR" = "Y" -o "$CHAR" = "y" ]; then echo "YES"elif [ "$CHAR" = "N" -o "$CHAR"="n" ]; then echo "NO"fi
Next time when you'd like to debug your script why it doesn't work, run is as: bash -x ./script.sh
or add -x
in your first line after bash
.
Check the following one-liner:
read CHAR && [ "${CHAR^^}" = "Y" ] && echo YES || echo NO
It's using bash parameter expansion, see: Case Insensitive comparision of strings in Shell script.
a case statement can be quite readable
read charcase ${char,} in y*) echo Yes;; n*) echo No;;esac
https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion