实现本地功能

Achieve Local Function

我想尝试实现的是在函数 中创建一个局部函数。同时,局部函数不会覆盖外层函数。下面是一个简单函数和一个带有参数的嵌套函数的示例来说明我的问题。

#!/bin/bash
usage() #<------------------------------- same function name
{
    echo "Overall Usage"
}

function_A()
{
    usage() #<--------------------------- same function name
    {
        echo "function_A Usage"
    }

    for i in "$@"; do
        case $i in
            --help)
                usage
                shift
                ;;
            *)
                echo "flag provided but not defined: ${i%%=*}"
                echo "See '[=10=] --help'."
                exit 0
            ;;
        esac
    done
}

function_A --help
usage

这是输出。

function_A Usage
function_A Usage

但我想要的是

function_A Usage
Overall Usage

是否可以在不改变它们(函数)名称和顺序的情况下实现?请?

注意:我试过local usage(),但似乎不适用于功能。

Bash 不支持本地函数,但根据您的特定脚本和体系结构,您可以通过子 shell 控制函数名称的范围。

通过将定义中的 {..} 替换为 (..),您将获得所需的输出。 usage 的新定义将仅限于功能,但例如对变量的任何更改:

#!/bin/bash
usage() 
{
    echo "Overall Usage"
}

function_A()
(                  # <-- Use subshell
    usage()
    {
        echo "function_A Usage"
    }

    for i in "$@"; do
        case $i in
            --help)
                usage
                shift
                ;;
            *)
                echo "flag provided but not defined: ${i%%=*}"
                echo "See '[=10=] --help'."
                exit 0
            ;;
        esac
    done
)

function_A --help
usage

扩展 的回答:

$ function zz() (:;)

$ declare -f zz

zz ()
{
    ( : )
}

你可以看到用括号而不是大括号定义一个函数只是shorthand用括号把函数的整个内部包裹起来。该函数实际上以其长格式标识。

https://www.tldp.org/LDP/abs/html/subshells.html https://www.gnu.org/software/bash/manual/html_node/Command-Grouping.html#Command-Grouping

来自man bash

Compound Commands

A compound command is one of the following:

(list) list is executed in a subshell environment (see COMMAND EXECUTION ENVIRONMENT below). Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list. ...

  1. 假设我们有 test.sh:
#!/usr/bin/sh

topFunction1() {
    # start subshell
    (


        innerFunction1() {
            echo "innerFunction1"
        }

        echo "topFunction1 can call $(innerFunction1) from within the subshell"


    )
    # end subshell


    innerFunction2() {
        echo "innerFunction2"
    }
}

topFunction2() {
    echo "topFunction2"
}
  1. 现在开始source test.sh

以下命令成功:

topFunction2

以下命令失败:

innerFunction1

innerFunction2

  1. 现在,如果我们执行 topFunction1,我们将得到包含 innerFunction1 输出的输出:

    topFunction1 can call innerFunction1 from within the subshell

此时以下命令成功:

topFunction1

topFunction2

innerFunction2

可以注意到,现在 innerFunction2 在调用 topFunction1 后它在全局可见。 但是 innerFunction1 它仍然是 'hidden' 用于子 shell 的调用,这可能是您想要的。

再次调用 innerFunction1 将失败。