user10724620
user10724620

Reputation:

Unable to invoke function as parameter in bash

Team,

I am unable to invoke functions as parameter while calling the script that contains that function. Can you please hint what am I missing.

#!/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

output expected:

10.1
10.2
10.3

Actual:

gfc is not a defined function

Upvotes: 0

Views: 120

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52506

Consider this script:

#!/usr/bin/env bash

echo "before declaration:"
type myfunc

myfunc() { echo "foo"; }

echo "after declaration:"
type myfunc

It prints the following:

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

You can't call a function before it is declared; all you have to do is move your function declarations to the top of your file.

Upvotes: 3

Related Questions