Determine if a function exists in bash

后端 未结 13 2498
再見小時候
再見小時候 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 17:51
    fn_exists()
    {
       [[ $(type -t $1) == function ]] && return 0
    }
    

    update

    isFunc () 
    { 
        [[ $(type -t $1) == function ]]
    }
    
    $ isFunc isFunc
    $ echo $?
    0
    $ isFunc dfgjhgljhk
    $ echo $?
    1
    $ isFunc psgrep && echo yay
    yay
    $
    
    0 讨论(0)
  • 2020-11-30 17:53

    It is possible to use 'type' without any external commands, but you have to call it twice, so it still ends up about twice as slow as the 'declare' version:

    test_function () {
            ! type -f $1 >/dev/null 2>&1 && type -t $1 >/dev/null 2>&1
    }
    

    Plus this doesn't work in POSIX sh, so it's totally worthless except as trivia!

    0 讨论(0)
  • 2020-11-30 17:55

    I think you're looking for the 'type' command. It'll tell you whether something is a function, built-in function, external command, or just not defined. Example:

    $ LC_ALL=C type foo
    bash: type: foo: not found
    
    $ LC_ALL=C type ls
    ls is aliased to `ls --color=auto'
    
    $ which type
    
    $ LC_ALL=C type type
    type is a shell builtin
    
    $ LC_ALL=C type -t rvm
    function
    
    $ if [ -n "$(LC_ALL=C type -t rvm)" ] && [ "$(LC_ALL=C type -t rvm)" = function ]; then echo rvm is a function; else echo rvm is NOT a function; fi
    rvm is a function
    
    0 讨论(0)
  • 2020-11-30 17:59

    This tells you if it exists, but not that it's a function

    fn_exists()
    {
      type $1 >/dev/null 2>&1;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-30 18:08
    $ g() { return; }
    $ declare -f g > /dev/null; echo $?
    0
    $ declare -f j > /dev/null; echo $?
    1
    
    0 讨论(0)
提交回复
热议问题