Determine if a function exists in bash

后端 未结 13 2634
再見小時候
再見小時候 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条回答
  •  一向
    一向 (楼主)
    2020-11-30 18:16

    If declare is 10x faster than test, this would seem the obvious answer.

    Edit: Below, the -f option is superfluous with BASH, feel free to leave it out. Personally, I have trouble remembering which option does which, so I just use both. -f shows functions, and -F shows function names.

    #!/bin/sh
    
    function_exists() {
        declare -f -F $1 > /dev/null
        return $?
    }
    
    function_exists function_name && echo Exists || echo No such function
    

    The "-F" option to declare causes it to only return the name of the found function, rather than the entire contents.

    There shouldn't be any measurable performance penalty for using /dev/null, and if it worries you that much:

    fname=`declare -f -F $1`
    [ -n "$fname" ]    && echo Declare -f says $fname exists || echo Declare -f says $1 does not exist
    

    Or combine the two, for your own pointless enjoyment. They both work.

    fname=`declare -f -F $1`
    errorlevel=$?
    (( ! errorlevel )) && echo Errorlevel says $1 exists     || echo Errorlevel says $1 does not exist
    [ -n "$fname" ]    && echo Declare -f says $fname exists || echo Declare -f says $1 does not exist
    

提交回复
热议问题