I'm trying to see if a value exists in a bash array. If so, do something. Else, do something else.
I can't figure out why this is always failing for me.
Basically start with two separate values, concatenate them with a delimiter, search against an array and if that entire string (delimiter and all) is in any of the array elements do something, else do something else.
#!/bin/bash
FNAME="JACK"
LNAME="BLACK"
SEARCHNAME=()
SEARCHNAME+="JACK-BLACK"
SEARCHNAME+="JOHN-JAMES"
SEARCHNAME+="CHRIS-TOPHER"
SEARCHNAME+="JEN-NAY"
NAME="${FNAME}-${LNAME}"
if [[ $NAME == *"${SEARCHNAME[@]}"* ]]; then
echo "PASSED"
else
echo "FAILED"
fi
echo "SEARCH IN: ${SEARCHNAME[@]}"
echo "FOR NAME: ${NAME}"
Results:
FAILED
SEARCH IN: JACK-BLACKJOHN-JAMESCHRIS-TOPHERJEN-NAY
FOR NAME: JACK-BLACK
I've also tried if [[ "${NAME}" == *"${SEARCHNAME[@]}"* ]]
but no difference... I'm missing something pretty obvious here and am thinking it might be with the way I'm declaring my array? I'd expect the lack of space between each array element (seen in array output) to not make a difference because of the wild-card characters?
echo "There are ${#SEARCHNAME[@]} members of the array"
at the end of your script. It will indicate1
member. The+=
assignments should look likeSEARCHNAME+=("JACK-BLACK")
.#!/bin/bash FNAME="JACK" LNAME="BLACK" SEARCHNAME=() SEARCHNAME+=("JACK-BLACK") SEARCHNAME+=("JOHN-JAMES") SEARCHNAME+=("CHRIS-TOPHER") SEARCHNAME+=("JEN-NAY") NAME="${FNAME}-${LNAME}" if [[ "${NAME}" == *"${SEARCHNAME[@]}"* ]]; then echo "PASSED" else echo "FAILED" fi echo "SEARCH IN: ${SEARCHNAME[@]}" echo "FOR NAME: ${NAME}" echo "ELEMENT COUNT: ${#SEARCHNAME[@]}"
ResultsFAILED SEARCH IN: JACK-BLACK JOHN-JAMES CHRIS-TOPHER JEN-NAY FOR NAME: JACK-BLACK ELEMENT COUNT: 4