Multi if or or similar

I'm trying to code a line (ksh) without much success along the lines of :-

If [ hostname = red or black or green or yellow or blue ]
then
.....etc
fi

I know i could use the case statement but i'm hoping someone may know a one liner or a simple workaround.

#!/usr/bin/ksh

hostname="${1}"

if [[ "${hostname}" = @(red|black|green|yellow|blue) ]] ; then
   echo "${hostname} - match"
else
   echo "${hostname} - no match"
fi
2 Likes

thanks it works perfectly, what do i need to read up on to better understand the logic behind it.

Thanks for pointing out how to do this in the Korn shell. I assume you meant to use $hostname (or ${hostname} ) in both places where you used ${color} .

yeah, sorry - color was the original variable name.

Read up on Korn shell regular expressions.

Actually, that is extended pattern matching, not a regular expression.

       A  pattern-list	is  a list of one or more patterns separated from each
       other with a & or |.  A & signifies that all patterns must  be  matched
       whereas	|  requires  that only one pattern be matched.	Composite pat-
       terns can be formed with one or more of the following sub-patterns:
	      ?(pattern-list)
		     Optionally matches any one of the given patterns.
	      *(pattern-list)
		     Matches zero or more occurrences of the given patterns.
	      +(pattern-list)
		     Matches one or more occurrences of the given patterns.
	      {n}(pattern-list)
		     Matches n occurrences of the given patterns.
	      {m,n}(pattern-list)
		     Matches from m to n occurrences of  the  given  patterns.
		     If  m  is	omitted,  0  will be used.  If n is omitted at
		     least m occurrences will be matched.
	      @(pattern-list)
		     Matches exactly one of the given patterns.
	      !(pattern-list)
		     Matches anything except one of the given patterns.

man ksh93

---
@squrcles: Why can't you use a case statement?

case $hostname in 
  (red|black|green|yellow|blue) echo "match"
esac
1 Like

Using the case statement was my fallback solution.

Alternatively - not better, but arguably easier to understand, and works in Bourne shell as well

if [ "$hostname" = "red" -o "$hostname" = "black" -o \
     "$hostname" = "green" -o  "$hostname" = "yellow" -o \
     "$hostname" = "blue" ] 
then 
.....etc
fi