Check if a function exists before executing it in the shell

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

Does the shell support a shell script? and how to do it?

+4
source share
3 answers

As stated in this comment , this should do this:

type -t function_name 

returns function if it is a function.

Test

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

Please note that type provides good info:

 $ type -t ls alias $ type -t echo builtin 
+6
source

POSIX does not provide arguments for the built-in type and does not specify its output. Best of all, except for a shell-specific solution, probably

 if type foo | grep -i function > /dev/null; then # foo is a function fi 
+2
source

You can always just try to execute a function. If it does not 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, a function may have the same name as another binary, and you cannot run this program if it is not obscured by the function.

0
source

Source: https://habr.com/ru/post/1494509/


All Articles