hpmistry19
hpmistry19

Reputation: 33

How to match substring with string in Bash

CIDR=$(echo "$DESCRIBE_VPC" | $JQ -r '.Vpcs[0].CidrBlock')
DEN_PARAM=$(aws ssm get-parameters --names "$DEN" --region $REGION)
GET_PARAM_VALUE=$(echo $PARAM | jq -r '.Parameters[].Value' | tr '[:upper:]' '[:lower:]')

DS_HOST=$(nslookup dsaws.com)
DS_STATUS=$?

if [ "$CIDR" == *"100."* ] && [ "$DS_STATUS" == 0 ] ## Ex: 100.1.172.1 /172.1.100.1
then
    retrieveAccInfo
elif [ "$CIDR" == *"172."* ] && [ "$DS_STATUS" != 0 ]
then
    retrieveAccInfo
fi

In Above example, I am trying to match substring "100." and "172." with a retrieved IP address. The above condition matches but if I get an IP: 172.1.1.100 that matches both conditions. What if I want IP address that exactly starts with 100 and 172 to match with the IPs, but not anywhere else in the string(IP).

Upvotes: 0

Views: 131

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15418

case is often a good option.

Corrected to only match 172 on nonzero DS_STATUS:

for DS_STATUS in 0 1
do for CIDR in 100.2.3.4 172.2.3.4 1.2.3.100 1.2.3.172
do echo "CIDR=$CIDR, DS_STATUS=$DS_STATUS"
   case "$DS_STATUS/$CIDR" in
   0/100[.]*)  echo "match"                   ;;
   0/172[.]*)  echo "no match, DS_STATUS = 0" ;;
   */172[.]*)  echo "alternate match"         ;;
   *) echo "no match"                         ;;
   esac
done
done

CIDR=100.2.3.4, DS_STATUS=0
match
CIDR=172.2.3.4, DS_STATUS=0
no match, DS_STATUS = 0
CIDR=1.2.3.100, DS_STATUS=0
no match
CIDR=1.2.3.172, DS_STATUS=0
no match
CIDR=100.2.3.4, DS_STATUS=1
no match
CIDR=172.2.3.4, DS_STATUS=1
alternate match
CIDR=1.2.3.100, DS_STATUS=1
no match
CIDR=1.2.3.172, DS_STATUS=1
no match

So,

case "$DS_STATUS/$CIDR" in
0/100[.]*) retrieveAccInfo            ;; # primary match
0/172[.]*) : no match, DS_STATUS is 0 ;; 
*/172[.]*) retrieveAccInfo            ;; # alternate match
        *) : no match at all          ;; 
esac

Upvotes: 0

ashish_k
ashish_k

Reputation: 1581

Try below:

for matching the IPs starting with 100: [[ "$CDR" =~ ^100.* ]] , and for matching the IPs starting with 172: [[ "$CDR" =~ ^172.* ]]

It's advisable to use if [[ condition ]] ,i.e double square brackets for if condition while using bash.

Upvotes: 1

Related Questions