Reputation: 43528
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?
Upvotes: 5
Views: 5425
Reputation: 72667
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
Upvotes: 1
Reputation: 531430
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.
Upvotes: 0
Reputation: 289835
As read in this comment, this should make it:
type -t function_name
this returns function
if it is a function.
$ 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
Upvotes: 7