无法在bash中调用函数作为参数

时间:2019-07-11 20:19:10

标签: bash

团队

在调用包含该函数的脚本时,无法将函数作为参数调用。能否请您提示我在想什么。

#!/bin/bash
if declare -f "$1" > /dev/null
then
  "$@"
else
  echo "$1 is not a defined function" >&2
  exit 1
fi

gfc() {
TEST_PERF_CLASS="GFC"
K8S_Node_Name=("10.1" "10.2" "10.3")
#declare -a K8S_Node_Name=("10.1" "10.2" "10.3")
if ([ "$TEST_PERF_CLASS" = "DFC" ] || [ "$TEST_PERF_CLASS" = "GFC" ]) && [ "$K8S_Node_Name" != "ALLCORDONED" ]; then
    for node in "${K8S_Node_Name[@]}"; do
      echo "$node"
      done
elif ([ "$TEST_PERF_CLASS" = "DFC" ] || [ "$TEST_PERF_CLASS" = "GFC" ]) && [ "$K8S_Node_Name" = "ALLCORDONED" ]; then
  echo "CORDONED"
else
    printf "Invalid NODE\n"
fi
}

dfc() {
TEST_PERF_CLASS="DFC"
K8S_Node_Name=("11.1" "110.2" "110.3")
if ([ "$TEST_PERF_CLASS" = "DFC" ] || [ "$TEST_PERF_CLASS" = "GFC" ]) && [ "$K8S_Node_Name" != "ALLCORDONED" ]; then
    for node in "${K8S_Node_Name[@]}"; do
      echo "$node"
      done
elif ([ "$TEST_PERF_CLASS" = "DFC" ] || [ "$TEST_PERF_CLASS" = "GFC" ]) && [ "$K8S_Node_Name" = "ALLCORDONED" ]; then
  echo "CORDONED"
else
    printf "Invalid NODE\n"
fi
> bash bash-call-function.sh gfc

预期输出:

10.1
10.2
10.3

实际:

gfc is not a defined function

1 个答案:

答案 0 :(得分:4)

考虑此脚本:

#!/usr/bin/env bash

echo "before declaration:"
type myfunc

myfunc() { echo "foo"; }

echo "after declaration:"
type myfunc

它打印以下内容:

before declaration:
./functest: line 4: type: myfunc: not found
after declaration:
myfunc is a function
myfunc () 
{ 
    echo "foo"
}

在声明函数之前不能调用它;您要做的就是将函数声明移到文件顶部。