Determine if a function exists in bash

后端 未结 13 2636
再見小時候
再見小時候 2020-11-30 17:39

Currently I\'m doing some unit tests which are executed from bash. Unit tests are initialized, executed and cleaned up in a bash script. This script usualy contains an init(

13条回答
  •  Happy的楠姐
    2020-11-30 18:17

    It boils down to using 'declare' to either check the output or exit code.

    Output style:

    isFunction() { [[ "$(declare -Ff "$1")" ]]; }
    

    Usage:

    isFunction some_name && echo yes || echo no
    

    However, if memory serves, redirecting to null is faster than output substitution (speaking of, the awful and out-dated `cmd` method should be banished and $(cmd) used instead.) And since declare returns true/false if found/not found, and functions return the exit code of the last command in the function so an explicit return is usually not necessary, and since checking the error code is faster than checking a string value (even a null string):

    Exit status style:

    isFunction() { declare -Ff "$1" >/dev/null; }
    

    That's probably about as succinct and benign as you can get.

提交回复
热议问题