meallhour
meallhour

Reputation: 15581

How to simplify an if-else statement matching IP address

I have the following If-Else statement which I want to simplify.

if [[ "$IP" == 192.* ]] || [[ "$IPAddr" == 193.* ]]
then
    data="correct data set"
fi 

I need to include more of [[ "$IP" == 192.* ]] and want to see if there is better way to do the same rather than using too many || statements

Upvotes: 0

Views: 978

Answers (3)

Paul Hodges
Paul Hodges

Reputation: 15313

You seem to be specifically attempting to match against multiple variables ($IP, $IPAddr).

If you mean $IP in both cases, then the solutions given are good.

Otherwise, each test is a distinct set of A and B comparisons, so a list of ||'s is likely still going to be your best bet. You can format them across lines for maintainability and readability, though...

if [[ "$IP"     == 192.* ]] || 
   [[ "$IPAddr" == 193.* ]]
then data="correct data set"
fi 

&& and || set up line-spanning context.

Upvotes: 0

Barmar
Barmar

Reputation: 781164

You can do it more easily with case.

case "$IP" in 
    192.* | 193.*) data="correct data set";;
esac

You can add more patterns separated by |.

Also, you can use a pattern like 19[23].* to match both strings.

Upvotes: 5

that other guy
that other guy

Reputation: 123490

Since this is a glob match, you can use a character range:

# 192.0.0.0 or 193.0.0.0
if [[  "$IP" == 19[23].* ]]
then echo "match"; fi

Or an extglob alternation:

# 192.0.0.0 or 10.0.0.0
if [[  "$IP" == @(192|10).* ]]
then echo "match"; fi

Upvotes: 2

Related Questions