Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a function exists before executing it in shell

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?

like image 614
MOHAMED Avatar asked Jul 31 '13 13:07

MOHAMED


2 Answers

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
like image 103
fedorqui 'SO stop harming' Avatar answered Oct 15 '22 10:10

fedorqui 'SO stop harming'


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
like image 36
Jens Avatar answered Oct 15 '22 11:10

Jens