代码之家  ›  专栏  ›  技术社区  ›  csexton

检查bash脚本中是否存在函数[duplicate]

  •  18
  • csexton  · 技术社区  · 16 年前

    如何确定函数是否已在bash脚本中定义?

    我试图使我的.bash_登录脚本在系统之间可移植,所以我想添加逻辑,只调用存在的函数。

    __git_ps1() PS1 仅当该系统上存在该功能时。此函数通常在中定义 git-completion.bash 它与git源代码一起提供,或者由ports/apt安装的bash完成脚本之一提供。

    9 回复  |  直到 7 年前
        1
  •  19
  •   Trevor Robinson    8 年前

    我意识到这是一个老问题,但其他答案都没有我想的那么简单。这使用 type -t (正如陈列维在评论中所建议的)作为一种有效的测试类型,但随后使用shell字符串比较而不是调用grep。

    if [ "$(type -t somefunc)" = 'function' ]; then
        somefunc arg1 arg2
    fi
    

    更进一步说,它也间接起作用:

    funcname=do_it_special_$somehow
    if [ "$(type -t $funcname)" != 'function' ]; then
        funcname=do_it_normal
    fi
    $funcname arg1 arg2
    
        2
  •  11
  •   chaos    12 年前
    if type __git_ps1 | grep -q '^function$' 2>/dev/null; then
        PS1=whatever
    fi
    
        3
  •  8
  •   Artem Barger    16 年前

    您可以使用以下方法进行操作:

    type function_name
    

    在中,如果函数定义存在,将返回函数定义。因此,您可以在输出是否为空时进行检查。

    更妙的是,我刚刚检查过它将输出该函数不存在,否则输出函数体。

        4
  •  6
  •   marcel    13 年前

    如果你需要 /bin/sh typeset declare 测试函数定义,因为它不是shell内置项。还有 -f 选择 type 在某些系统上可能不可用。

    我提出的解决方案部分已包含在其他答案中:

    isFunction() {
      type $1 | head -1 | egrep "^$1.*function\$" >/dev/null 2>&1;
      return;
    }
    
    isFunction __git_ps1 && PS1=__git_ps1
    
        5
  •  5
  •   Fritz G. Mehner    16 年前

    回声$?

    $? 如果函数存在,则结果的值为0,否则为1

        6
  •  3
  •   Jacobo de Vera    15 年前

    function function_exists
    {
        FUNCTION_NAME=$1
    
        [ -z "$FUNCTION_NAME" ] && return 1
    
        declare -F "$FUNCTION_NAME" > /dev/null 2>&1
    
        return $?
    }
    

    因此,稍后在我的脚本中,我可以很容易地看到发生了什么:

    if function_exists __git_ps1
    then
        PS1=__git_ps1
    fi
    

    甚至是仍然可读的一行:

    function_exists __git_ps1 && PS1=__git_ps1
    
        7
  •  1
  •   tim    14 年前

    help compgen
    
    compgen -A function
    
    compgen -A function myfunc 1>/dev/null && echo 'myfunc already exists' || exit 1
    
        8
  •  0
  •   Jaime Soriano    16 年前
    if declare -F | grep __git_ps1$
    then
        PS1=whatever
    fi
    
        9
  •  0
  •   Reed Hedges    13 年前

    注意,busybox(最简单的多合一shell实现,在Windows上很有用)有“type”,但“type-t”打印的东西不正确,所以我只检查type的返回值,看看是否有东西可以调用。busybox也没有声明。