Junior
Junior

Reputation: 23

test a string against each element of an array

I'm new to bash shell scripting and it is my first day and first time to post a question here in stackoverflow. I already searched the archive to no avail. I hope someone can help me.

I have an array like this

declare -a SID=("mydb1" "mydb2" "mydb3")

In my script, the user will be prompted to enter a string and it will be stored in $DBNAME variable.

For example a user entered "mydb2" (without quote), this will be stored in $DBNAME variable.

I want to create a loop and I want the input of the user to be tested against each element of the ${SID[@]} variable.

And when a match found, it will exit from the loop and continue with the next command in a script.

Please help me create a script to match a string value against each element of an array variable.

Any help would be highly appreciated. Thank you!

Upvotes: 2

Views: 3206

Answers (3)

Jonathan Hall
Jonathan Hall

Reputation: 79604

If all you want to do is check that the user entered a valid dbname, do this:

declare -a SID=("mydb1" "mydb2" "mydb3")
case " ${SID[*]} " in
    *\ $DBNAME\ *)
        echo Entered a correct DB name! Good job, pal!
        ;;
    *)
        echo Try again
        ;;
 esac

This can lead to false-positives in cases where you allow space-containing user-input. If this is a concern, you can solve the problem by using a non-space delimiter that is not allowed in the user's input. For example:

case ".mydb1.mydb2.mydb3." in
    *.$DBNAME.*)

If your user input is completely open-ended, and unvalidated, then a for loop is probably your best bet, as explained in @glennjackson's answer.

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246837

@Flimzy's approach is good. The correct way to use a for-loop is

for db in "${SID[@]}"; do
  if [[ $db = $DBNAME ]]; then
    echo yes
    break
  fi
done

Upvotes: 5

William Pursell
William Pursell

Reputation: 212258

If all you want is to check that $DBNAME is an entry is $SID, the easiest thing to do is probably:

if echo ${SID[@]} | grep -wq "$DBNAME"; then
   # DBNAME is in SID array
fi

Note that -w and -q are non-standard options to grep, so you might want:

if echo ${SID[@]} | grep "\<$DBNAME\>" > /dev/null; then
   # DBNAME is in SID array
fi

This will fail if any of the entries in SID contain spaces, and other odd characters will undoubtedly cause problems as well.

Upvotes: 0

Related Questions