Determine if a function exists in bash

后端 未结 13 2609
再見小時候
再見小時候 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:00

    Borrowing from other solutions and comments, I came up with this:

    fn_exists() {
      # appended double quote is an ugly trick to make sure we do get a string -- if $1 is not a known command, type does not output anything
      [ `type -t $1`"" == 'function' ]
    }
    

    Used as ...

    if ! fn_exists $FN; then
        echo "Hey, $FN does not exist ! Duh."
        exit 2
    fi
    

    It checks if the given argument is a function, and avoids redirections and other grepping.

提交回复
热议问题