0

I created an SMS autoresponder script, currently it allows all phone numbers to be replied from my machine, now I want to filter only a specific phone number, so when other phone numbers that are not in the list, my machine ignores it.

#!/bin/bash
PhoneNumberFilter="yes"
PhoneNumber[0]="08123"
PhoneNumber[1]="08321"
PhoneNumber[2]="12345"

MyPhoneNumber="08321"
echo "My phone number is: $MyPhoneNumber"
echo "all numbers: ${PhoneNumber[@]}"
if [[ "$PhoneNumberFilter" == "yes" ]] && [[ *"$MyPhoneNumber"* == "${PhoneNumber[*]}" ]]; then
    echo "it works"
    echo "My phone number is in the list of arrays"
    echo "Send SMS to my phone number only"
else
    echo "it doesn't work, my phone number is not in the list"
    echo "ignore it"
fi

How do I display the it works part? when I execute that script it always displays the it doesn't work part.

4
  • The efficient way to do this would be to store the number in the key field, not the value field; then it's an O(1) lookup. Commented Feb 16, 2015 at 6:16
  • I still don't get it, sorry I'm still learning, how should I implement that? Commented Feb 16, 2015 at 6:17
  • I fixed it with the command case thanks :D Commented Feb 16, 2015 at 15:45
  • Removed my prior comment -- I got that wrong. The Right Thing is actually [[ " ${PhoneNumber[*]} " = *" $MyPhoneNumber "* ]] -- with the whitespace. That's still buggy (prone to false positives) if array values can contain spaces, though, hence the associative array approach both scaling better and being more reliable. Commented Feb 16, 2015 at 16:15

1 Answer 1

0

Store the number in the key, not the value, within your array. As given below, this requires bash 4.0 or newer (for associative arrays) -- though for purely-numeric values, it could also be implemented without them (with the caveat that base-10 parsing needs to be ensured even when values start with 0).

declare -A phoneNumbers=( [08123]=1 [08321]=1 [12345]=1 )
myPhoneNumber=08321

if [[ ${phoneNumbers[$myPhoneNumber]} ]]; then
  echo "Found"
fi
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.