Bash에서 배열의 요소 찾기

Bash에서 배열의 요소 찾기

다음 코드를 사용하여 먼저 배열을 2개의 배열로 분할한 다음 두 분할 배열 모두에서 "Alchemist"와 "Axe"라는 두 요소가 있는지 검색합니다.

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
}

하지만 다음과 같은 오류가 발생합니다.

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

14행과 18행은 각각 if [ array_contains2 $team1 "Alchemist" "Axe" ]및 입니다 if [ array_contains2 $team2 "Alchemist" "Axe" ].

IFS 오류 때문입니다. 그렇지 않다면 오류의 원인은 무엇입니까?

답변1

문제는 if 문에 있다고 생각합니다. 함수를 사용하는 경우에는 대괄호가 필요하지 않은 것 같습니다. 이것을 봐주세요:

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

나는 당신이 이렇게 하고 싶어할 것이라고 믿습니다:

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

답변2

이미 함수를 사용하고 있는데 왜 쉘 배열 대신 bash 배열만 사용하도록 제한하시겠습니까 $@?

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

관련 정보