如何在shell脚本中从for循环调用函数

1 bash shell-script

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)
}
Run Code Online (Sandbox Code Playgroud)

尝试调用 check_item1 和 check_item2 函数时出现错误 check_: command not found。

ilk*_*chu 5

array_item= (item1 item2)
Run Code Online (Sandbox Code Playgroud)

不要在=in 分配周围放置空格,它不起作用。这也给了我一个关于括号的语法错误。check_: command not found如果数组元素未设置或为空,您可能会收到错误消息。

for (( i=0; i<${array_item[@]}; i++ ))
Run Code Online (Sandbox Code Playgroud)

${array_item[@]}扩展到数组的所有元素,我想你想要${#array_item[@]}元素的数量。如果数组为空,这也应该给出一个错误,因为比较的另一个操作数将丢失。

for (( ... )) { cmds...}构造似乎在 Bash 中有效,但手册仅描述了通常的for (( ... )) ; do ... ; done构造。

或者只是for x in "${array_item[@]}" ; do ... done用来循环数组的值。

如果您在循环时确实需要索引,那么在技术上循环可能会更好"${!array_item[@]}",因为索引实际上不需要是连续的。这也适用于关联数组。