Exiting the script if the character is not recognized

Below is the script that i'm using but i'm getting an error,

echo -n "Read the letter >(enter a or b or c) "
read letter

if [ $letter -ne a ] || [ $letter -ne b ] || [ $letter -ne c ];
then
        echo "unacceptable character"
else
echo "Character Accepted"
fi

if the character entered is not equal to a or b or c, the script should exit with the message displayed on the screen.

Any help will be appreciated.

Thanks

       arg1 OP arg2
              OP  is  one  of  -eq,  -ne, -lt, -le, -gt, or -ge.  These arithmetic binary operators
              return true if arg1 is equal to, not equal to, less than,  less  than  or  equal  to,
              greater  than,  or greater than or equal to arg2, respectively.  Arg1 and arg2 may be
              positive or negative integers.
1 Like
#!/bin/bash

echo -n "Read the letter >(enter a or b or c) "
read letter

# One easiest way to Compare 
for i in a b c; do
	[ "$i" = "$letter" ] && break
done

# ok will be zero if true else 1
ok=$?

# Compare
if [ $ok -ne 0 ];then
	echo "unacceptable character"
else
	echo "Character Accepted"
fi

Syntax for string

# Syntax for string 

a="A"; b="A";

if    [ "$a" != "$b" ]; then
	echo "Not Equal"
elif  [ "$a" = "$b" ]; then
    	echo "Equal"
fi
1 Like

Hi Akshay.

your code, worked.
Thanks a ton.

Use

if [ $letter != a ] && [ $letter != b ] && [ $letter != c ]

in your code.

Using a case statement:

#!/bin/bash

echo -n "Read the letter >(enter a or b or c) "
read letter

case $letter in
  a|b|c)  echo "Character Accepted"
          ;;
      *)  echo "Unacceptable Character"
          exit
          ;;
esac
1 Like

I like the case-statement for this task. You can also easily add another block to fine tune the error handling, e.g. ??*) echo Too many characters;; .

Regards,
Alister