5

I want to check if a function exist or not before executing it in the shell script.

Does script shell support that? and how to do it?

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • 2
    See http://stackoverflow.com/questions/85880/determine-if-a-function-exists-in-bash - but you mention ash, not sure if that solution works in ash as well. – fvu Jul 31 '13 at 13:44

3 Answers3

7

As read in this comment, this should make it:

type -t function_name

this returns function if it is a function.

Test

$ type -t f_test
$ 
$ f_test () { echo "hello"; }
$ type -t f_test
function

Note that type provides good informations:

$ type -t ls
alias
$ type -t echo
builtin
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
2

POSIX does not specify any arguments for the type built-in and leaves its output unspecified. Your best bet, apart from a shell-specific solution, is probably

if type foo | grep -i function > /dev/null; then
   # foo is a function
fi
Jens
  • 69,818
  • 15
  • 125
  • 179
0

You can always just try executing the function. If it doesn't exist, the exit status of the command will be 127:

$ myfunction arg1 arg2 || {
>  if [ $? -ne 127 ]; then
>    echo Error with my function
>  else
>    echo myfunction undefined
>  fi; }

Of course, the function may have the same name as another binary, and you may not want to run that program if it is not shadowed by the function.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    What if the function is destructive (think `make clean`)? What if the function itself returns 127 or its last command does? I wouldn't want to run a reboot function just to see if it exists... – Jens Aug 02 '13 at 06:56
  • 1
    The first point is valid. I would argue that if the function itself returns 127, that's a bug in the function, as it is defined by POSIX to mean "command not found". I was working on the assumption that if he's going to call it if it exists, there's no harm in just trying to call it first. – chepner Aug 02 '13 at 12:37