3

I am wondering if it is possible to check the existence of a function within a script. I.e. at the moment, I have a few if's to check a value and then call a function, but was wondering if it is possible to do something like:

if[[ ${function_name}Function exists ]]
then
.....call function etc
fi

where there may be a function within the script

Is this possible?

Pectus Excavatum
  • 3,593
  • 16
  • 47
  • 68

3 Answers3

6
if type Function &>/dev/null
then
   ...
fi

Example:

$ type f 2>& /dev/null && echo f exists || echo f does not exist 
f does not exist
$ f()
> {
> echo 1
> }
$ type f >& /dev/null && echo f exists || echo f does not exist 
f exists

What do I here?

  • Here I check first if function f exists; it does not exist, ok.
  • Then I create it.
  • Then I check again, if it exists. It exists, ok.

Without additional checks you can't say directly if it is a command, or an alias, or a function; all that you known if this entity exists or don't.

If you want to run functions and only functions, you must make your check stricter:

type Function | grep -q '^function$' 2>/dev/null

In bash you can also use declare -F function. (Thanks to that other guy)

Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
1

declare -F shows you all functions declared in Bash. From there it's a simple declare -F my_function && echo 'function exists'

l0b0
  • 55,365
  • 30
  • 138
  • 223
0

The most reliable method that I have found is

FuncName='MyFunction'
if typeset -f "${FuncName}" > /dev/null; then
  "${FuncName}"
fi

BTW, this approach works fine in zsh too.

Victor Yarema
  • 1,183
  • 13
  • 15