functionshellshposix

How to determine whether a function exists in a POSIX shell?


This is basically the same question as Determine if a function exists in bash, except that this time it's not aiming at Bash, but at a POSIX shell:

How to determine whether a shell function with a given name exists?

It seems that none of the typical built-ins like type are mandated by POSIX, so the matter is more difficult or maybe even impossible.


Solution

  • You can use command for this in shells that implement the 2013 version of POSIX, or the User Portability Utilities option of the older spec:

    isFunction() { 
      command -V "$1" 2>/dev/null | grep -qwi function
    }
    

    However, note that the spec doesn't actually dictate the form of the command's output. It requires that functions be identified as such, so it is highly likely that the output will include the word function if and only if the requested name is a function, but it is not strictly guaranteed. The above solution can be fooled pretty easily (see @jiliagre's comment).

    A different part of the spec mandates a type command that does much the same thing (with the same caveats about unspecified output format). Oddly, it's not listed as one of the commands required to be a shell builtin, but as the informational notes say, it pretty much has to be one in order to work as specified.