Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
2  
Youre quoting the wrong stuff. "Alchemist" and "Axe" dont expand, but $element $seeking and $team do. –  mikeserv Apr 19 at 9:16

2 Answers 2

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:

http://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
share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.