![Bash에서 배열의 요소 찾기](https://linux55.com/image/53261/Bash%EC%97%90%EC%84%9C%20%EB%B0%B0%EC%97%B4%EC%9D%98%20%EC%9A%94%EC%86%8C%20%EC%B0%BE%EA%B8%B0.png)
다음 코드를 사용하여 먼저 배열을 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 문에 있다고 생각합니다. 함수를 사용하는 경우에는 대괄호가 필요하지 않은 것 같습니다. 이것을 봐주세요:
나는 당신이 이렇게 하고 싶어할 것이라고 믿습니다:
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