kumar_m_kiran
kumar_m_kiran

Reputation: 4022

shell ksh function parameter contains another function name to call

I am trying to write a generic function (say holder) - which will take the first parameter name as another function name (like f1,f2,f3,f4...) and calls them based on some condition. Like


#!/bin/ksh
function f1
{
echo "f1"
return 7
}

function f2
{
echo "f2"
return 8
}

function holder
{
fptr=$1
`${fptr}`
ret=$?
echo $ret
}

holder "f1"
holder "f2"

Now above sample works. However, sometimes the evaluation line ${fptr} , strange failures occur with details of stack. I suspect the way I am calling the function might have some issues.Above code is a sample mock code, actual code contains complex f1,f2 logic.

  1. Is it possible to handle such kind of indirect invocation?
  2. Is the "function calling" in holder class correct? or should it be handled in a separate way?

Upvotes: 0

Views: 402

Answers (1)

devnull
devnull

Reputation: 123608

It's hard to figure what causes sporadic failures in your case. However, there are a couple of things that you might want to change:

  1. You probably want to use eval instead of backticks.
  2. You can refer to the function name using $0

Executing the modified code:

function f1 {
  echo $0
  return 7
}

function f2 {
  echo $0
  return 8
}

function holder {
  eval "$1"
  echo $?
}

holder "f1"
holder "f2"

returns:

f1
7
f2
8

Upvotes: 1

Related Questions