0

I am using the following code to first split an array into 2 and then search if 2 elements "Alchemist" and "Axe" are present in each of the two split arrays.

tempifs=$IFS
    IFS=,
    match=($i)
    IFS=$tempifs
    team1=( "${match[@]:0:5}" )
    team2=( "${match[@]:5:5}" )
        if [ array_contains2 $team1 "Alchemist" "Axe" ]
    then
    echo "team1 contains"
        fi
    if [ array_contains2 $team2 "Alchemist" "Axe" ]
    then
    echo "team2 contains"
        fi  

array_contains2 () { 
    local array="$1[@]"
    local seeking=$2
    local seeking1=$3
    local in=0
    for element in "${array[@]}"; do
        if [[ $element == $seeking && $element == $seeking1]]
    then
            in=1
            break
        fi
    done
    return $in
}

But I am getting the following error -

/home/ashwin/bin/re: line 18: [: Alchemist: binary operator expected
/home/ashwin/bin/re: line 14: [: too many arguments

Lines 14 and 18 are if [ array_contains2 $team1 "Alchemist" "Axe" ] and if [ array_contains2 $team2 "Alchemist" "Axe" ] respectively.

Is the error because of IFS. If not what is the cause for the error?

1
  • 2
    Youre quoting the wrong stuff. "Alchemist" and "Axe" dont expand, but $element $seeking and $team do. Commented Apr 19, 2014 at 9:16

2 Answers 2

3

I believe the problem has to do with your if statements. It looks like if you're using a function you don't need the square brackets. Please see this:

https://stackoverflow.com/questions/8117822/in-bash-can-you-use-a-function-call-as-a-condition-in-an-if-statement

I believe that you'll want to instead do:

if array_contains2 $team1 "Alchemist" "Axe"; then
    echo "This is true"
fi
0
1

You're already using a function, why would you limit yourself to bash arrays rather than use the shell $@ array?

bash_array=(one two three)
set -- $bash_array
printf %s\\n "$@"
    #output
one
two
three

IFS=/ ; echo "$*" ; echo "$@"
    #output 
/one/two/three
one two three

unset IFS ; in=$* ; 

[ -n "${in#"${in%$2*}"}" ] && echo "$2 is in $@" || echo nope
    #output
two is in one two three
1
  • Would you explain your answer? What is the type of $in toward the end (a string, not an array, right?)? Are you finding an element by looking through a STRING representation of the array? Commented Mar 13, 2022 at 20:20

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.