Check if a function exists before executing it in shell
Asked Answered
C

3

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?

Catalan answered 31/7, 2013 at 13:42 Comment(1)
See #86380 - but you mention ash, not sure if that solution works in ash as well.Criticize
H
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
Halfhour answered 31/7, 2013 at 13:44 Comment(2)
Is -t available in ash? It's not POSIX, so I wonder if it is a bash extension.Hasseman
To be honest, I don't know it, @chepner.Halfhour
S
1

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
Selfrestraint answered 31/7, 2013 at 19:40 Comment(1)
Do not use this. Depending on the language of the user the word "function" may not exists in the output.Ephesus
H
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.

Hasseman answered 31/7, 2013 at 19:9 Comment(2)
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...Selfrestraint
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.Hasseman

© 2022 - 2024 — McMap. All rights reserved.