쉘 스크립트의 for 루프에서 함수를 호출하는 방법

쉘 스크립트의 for 루프에서 함수를 호출하는 방법
array_item= (item1 item2)
#function
check_item1 ()
{
 echo "hello from item1"
}
check_item2 ()
{
echo "Hello from item2"
}
#calling functions
for (( i=0; i<${array_item[@]}; i++ ))
{
 check_${array_item[$i]}  # (expecting check_item1 then check_item2 funtion will be called)
}

check_item1 및 check_item2 함수를 호출하려고 하면 check_: 명령을 찾을 수 없다는 오류가 발생합니다.

답변1

array_item= (item1 item2)

할당 주위에 공백을 넣지 마십시오 =. 작동하지 않습니다. 또한 이로 인해 괄호에 대한 구문 오류가 발생합니다. check_: command not found배열 요소가 설정되지 않았거나 비어 있으면 오류가 발생할 수 있습니다 .

for (( i=0; i<${array_item[@]}; i++ ))

${array_item[@]}배열의 모든 요소로 확장됩니다. ${#array_item[@]}요소 수를 원한다고 생각합니다. 배열이 비어 있으면 비교에 대한 다른 피연산자가 누락되므로 오류가 발생합니다.

for (( ... )) { cmds...}구성은 Bash에서 작동하는 것처럼 보이지만 매뉴얼에서는 일반적인 for (( ... )) ; do ... ; done구성만 설명합니다.

또는 for x in "${array_item[@]}" ; do ... done배열 값을 반복하는 데 사용합니다.

루프하는 동안 인덱스가 필요한 경우 "${!array_item[@]}"인덱스가 실제로 연속적일 필요는 없으므로 루프를 반복하는 것이 기술적으로 더 나을 수 있습니다. 이는 연관 배열에서도 작동합니다.

답변2

for 루프를 변경하십시오.

for index in ${array_item[*]}
    do
       check_$index
    done

전체 스크립트

#!/bin/bash

array_item=(item1 item2)

#function
check_item1 ()
{
   echo "hello from item1"
}
check_item2 ()
{
   echo "Hello from item2"
}   

for index in ${array_item[*]}
    do
       check_$index
    done

주의: 또한 다음과 같은 펑키한 구성을 사용할 수 있습니다.

${array_item[*]}         # All of the items in the array
${!array_item[*]}        # All of the indexes in the array
${#array_item[*]}        # Number of items in the array
${#array_item[0]}        # Length of item zero

관련 정보