本文介绍了符合POSIX的方法来查看是否在sh脚本中定义了功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种确定函数是否正确的正确方法.符合POSIX的方式.

I'm after THE proper way to see if a function is defined or not. A POSIX compliant way.

__function_defined() {
    FUNC_NAME=$1
    d=$(declare -f $FUNCNAME)

    if [ "${DISTRO_NAME_L}" = "centos" ]; then
        if typeset -f $FUNC_NAME &>/dev/null ; then
            echo " * INFO: Found function $FUNC_NAME"
            return 0
        fi

    # Try POSIXLY_CORRECT or not
    elif test -n "${POSIXLY_CORRECT+yes}"; then
        if typeset -f ${FUNC_NAME} >/dev/null 2>&1 ; then
            echo " * INFO: Found function $FUNC_NAME"
            return 0
        fi
    else
        # Arch linux seems to fall here
        if $( type ${FUNC_NAME}  >/dev/null 2>&1 ) ; then
            echo " * INFO: Found function $FUNC_NAME"
            return 0
        fi
    echo " * INFO: $FUNC_NAME not found...."
    return 1
}

根据debian的 checkbashisms 脚本,以上所有内容均被视为bash'ism.

All of the above are considered bash'isms according to debian's checkbashisms script.

尝试grep脚本也不行.例如:

Trying to grep the script is also not ok. for example:

    if [ "$(grep $FUNC_NAME $(dirname $0)/$(basename $0))x" != "x" ]; then
        # This is really ugly and counter producing but it was, so far, the
        # only way we could have a POSIX compliant method to find if a function
        # is defined within this script.
        echo " * INFO: Found function $FUNC_NAME"
        return 0
    fi

不起作用,因为脚本也应该像这样工作:

won't work because the script is also supposed to work like:

wget --no-check-certificate -O - http://URL_TO_SCRIPT | sudo sh

那么,执行此操作的正确的,符合POSIX的正确方法是什么?

So, what's the proper, POSIX compliant way to do this?

请简单使用sh,不要使用bash,ksh,不要使用其他shell,而应该使用普通sh.哦,也没有实际尝试运行该功能:)

Plain sh please, no bash, no ksh, no other shell, just plain sh. Oh, and without actually trying to run the function too :)

有可能吗?

if [ "$(command -v $FUNC_NAME)x" != "x" ]; then
    echo " * INFO: Found function $FUNC_NAME"
    return 0
fi

现在的问题,是否有更好的解决方案?

推荐答案

我找到了一种POSIX兼容方式

if [ "$(command -v $FUNC_NAME)x" != "x" ]; then
    echo " * INFO: Found function $FUNC_NAME"
    return 0
fi

现在的问题,是否有更好的解决方案?

这篇关于符合POSIX的方法来查看是否在sh脚本中定义了功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 16:28