Fork me on GitHub

Project Notes

Function Inference

How to test for the presence of functions in order to branch to arbitrary functions by name.

:arrow_forward: return to the Catalog

Notes

In shell scripts, it is often useful to branch to a specific function given a parameter that matches the function name in some way.

A naive approach is to encode all the options with a case statement. For example:

function run_a() {}
function run_b() {}
name=$1
case ${name} in
a|b)
  run_${name}
*}
echo "no match"
;;
esac

But that is a bit tedious, because each new function not only needs to be defined, but also added to the case statement.

The Trick

The type builtin command can be used to test for shell functions (among other things). For example:

if type  -t "${function_name}" 2>/dev/null | grep -q 'function'
then
  echo "calling the function now we know it exists.."
  $function_name
else
  echo "there is no function by that name"
fi

Test Code

The test.sh script demonstrates the technique in a bit more detail. Here’s a console transcript of it in action:

console_test

Credits and References

About LCK#21 Bash
Project Source on GitHub Return to the Project Catalog

This page is a web-friendly rendering of my project notes shared in the LittleCodingKata GitHub repository.

LittleCodingKata is my collection of programming exercises, research and code toys broadly spanning things that relate to programming and software development (languages, frameworks and tools).

These range from the trivial to the complex and serious. Many are inspired by existing work and I'll note credits and references where applicable. The focus is quite scattered, as I variously work on things new and important in the moment, or go back to revisit things from the past.

This is primarily a personal collection for my own edification and learning, but anyone who stumbles by is welcome to borrow, steal or reference the work here. And if you spot errors or issues I'd really appreciate some feedback - create an issue, send me an email or even send a pull-request.