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?
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?
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
-t
available in ash
? It's not POSIX, so I wonder if it is a bash
extension. –
Hasseman 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
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.
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... –
Selfrestraint © 2022 - 2024 — McMap. All rights reserved.