Home > OS >  Shell Script Syntax Error if [[ $Char == [A-Z] -o $Char == [a-z] ]]
Shell Script Syntax Error if [[ $Char == [A-Z] -o $Char == [a-z] ]]

Time:03-22

In the below mentioned code the line if [[ $Char == [A-Z] -o $Char == [a-z] ]] shows the following error

symbol.sh: line 2: syntax error in conditional expression

symbol.sh: line 2: syntax error near `-o'

read -p "Enter the Character " Char
if [[ $Char == [A-Z] -o $Char == [a-z] ]] 
then 
    echo "The Character entered is an ALPHABET"
elif [[ $Char == [0-9] ]]
then
    echo "The Character entered is a NUMBER"
else
    echo "The Character entered is a Special Symbol"    
fi  

I tried doing it the other way and it works fine.

read -p "Enter the Character " Char
if [[ $Char == [a-z] ]] 
then 
    echo "The Character entered is an ALPHABET"
elif [[ $Char == [A-Z] ]] 
then 
    echo "The Character entered is an ALPHABET"
elif [[ $Char == [0-9] ]]
then
    echo "The Character entered is a NUMBER"
else
    echo "The Character entered is a Special Symbol"    
fi      

I just want to know what is wrong with this line of code if [[ $Char == [A-Z] -o $Char == [a-z] ]]

CodePudding user response:

You've mixed up the syntax for the various comparison operators. The test (or [) command does use the -o syntax to be an "or" operator, but the [[ conditional construct has a different syntax; there, -o checks to see if the given shell option is enabled. To get an "or" with [[, use the || syntax between tests:

if [[ $Char == [A-Z] ]] || [[ $Char == [a-z] ]] 
then 
# ...

You could alternatively use the bash syntax that tests against your locale's character classes:

#!/bin/bash
read -p "Enter the Character " Char
if [[ $Char == [[:alpha:]] ]]
then
    echo "The Character entered is an ALPHABET"
elif [[ $Char == [[:digit:]] ]]
then
    echo "The Character entered is a NUMBER"
else
    echo "The Character entered is a Special Symbol"
fi
  • Related