【问题标题】:shell bash, can you check if a function exists [duplicate]shell bash,你能检查一个函数是否存在[重复]
【发布时间】:2014-02-10 01:37:01
【问题描述】:

我想知道是否可以检查脚本中是否存在函数。 IE。目前,我有一些 if 来检查一个值,然后调用一个函数,但想知道是否可以执行以下操作:

if[[ ${function_name}Function exists ]]
then
.....call function etc
fi

脚本中可能有函数的地方

这可能吗?

【问题讨论】:

    标签: string bash function shell grep


    【解决方案1】:

    我找到的最可靠的方法是

    FuncName='MyFunction'
    if typeset -f "${FuncName}" > /dev/null; then
      "${FuncName}"
    fi
    

    顺便说一句,这种方法在zsh 也适用。

    【讨论】:

      【解决方案2】:
      if type Function &>/dev/null
      then
         ...
      fi
      

      例子:

      $ type f 2>& /dev/null && echo f exists || echo f does not exist 
      f does not exist
      $ f()
      > {
      > echo 1
      > }
      $ type f >& /dev/null && echo f exists || echo f does not exist 
      f exists
      

      我在这里做什么?

      • 这里我先检查函数f是否存在;不存在,好吧。
      • 然后我创建它。
      • 然后我再次检查它是否存在。它存在,好的。

      如果没有额外的检查,你不能直接说出它是命令、别名还是函数;如果该实体存在或不存在,您所知道的一切。

      如果你想运行函数并且只运行函数,你必须让你的检查更严格:

      type Function | grep -q '^function$' 2>/dev/null
      

      在 bash 中,您还可以使用 declare -F function。 (感谢那个人)

      【讨论】:

      • +1。更简洁地说,将该建议合并到一个测试中:if [[ $(type -t $funcname 2>/dev/null) == function ]]; then echo "I'm a function"; fi
      • declare -F function > /dev/null
      • “bash 中没有检查函数是否存在这样的操作” - 是的。见help declare
      • @thatotherguy:谢谢你的提示!我已经更新了答案
      【解决方案3】:

      declare -F 显示在 Bash 中声明的所有函数。从那里是一个简单的declare -F my_function && echo 'function exists'

      【讨论】:

        猜你喜欢
        • 2012-12-31
        • 2012-05-26
        • 1970-01-01
        • 1970-01-01
        • 2011-09-22
        相关资源
        最近更新 更多