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.

Lin
  • 1,421
  • 4
  • 15
  • 20
  • 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. – Charles Duffy Feb 16 '15 at 06:16
  • I still don't get it, sorry I'm still learning, how should I implement that? – Lin Feb 16 '15 at 06:17
  • I fixed it with the command `case` thanks :D – Lin Feb 16 '15 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. – Charles Duffy Feb 16 '15 at 16:15

1 Answers1

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
Charles Duffy
  • 235,655
  • 34
  • 305
  • 356