如何在shell腳本中的for循環中呼叫函數

如何在shell腳本中的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_: command not find 。

答案1

array_item= (item1 item2)

不要在=in 賦值周圍放置空格,它不起作用。這也給了我一個關於括號的文法錯誤。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

相關內容