2

Bash is “kind of function programming language” it dose not have classes. I managed to use encapsulation with Closures, but I want also to do some introspection to find also docker_ parent/super/base function (If you know add comments to define this correctly).

I managed this but with a dirty hack super=${FUNCNAME}. Is there any solution to use kind of PARENT_FUNCNAME? I have such file docker_.sh:

#!/usr/bin/env bash
function docker_ {
    local super=${FUNCNAME}
    function hello {
        echo "INFO" "do ${super}${FUNCNAME}"
    }
    function install {
        echo "INFO" "do ${super}${FUNCNAME}"
        #sudo curl -sSL https://get.docker.com/ | sh || exit 1
    }
    function run {
        echo "INFO" "do ${super}${FUNCNAME}"
        #docker run -d -p 3306:3306 ${DOCKER_IMAGE_NAME} /docker.sh run_mysql
    }
    ${@}
}
${@}

Got some results:

$ ./docker_.sh docker_ hello
INFO do docker_hello

$ ./docker_.sh docker_ run
INFO do docker_run

$ ./docker_.sh docker_ install
INFO do docker_install

Solved

use

${FUNCNAME[1]}
${FUNCNAME[@]:0:${#FUNCNAME[@]}-1} get all list beside main

code:

#!/usr/bin/env bash
function docker_ {
    function hello {
        echo "INFO" "do ${FUNCNAME[1]} ${FUNCNAME}"
    }
    function install {
        echo "INFO" "do > ${FUNCNAME[@]:0:${#FUNCNAME[@]}-1} "
        #sudo curl -sSL https://get.docker.com/ | sh || exit 1
    }
    function run {
        echo "INFO" "do > ${FUNCNAME[@]:0:${#FUNCNAME[@]}-1} "
        #docker run -d -p 3306:3306 ${DOCKER_IMAGE_NAME} /docker.sh run_mysql
    }
    ${@}
}
${@}

Got some results:

    ➜ ./docker_.sh docker_ hello  
    INFO do docker_ hello
    ➜ ./docker_.sh docker_ install
    INFO do > install docker_ 
    ➜ ./docker_.sh docker_ run    
    INFO do > run docker_ 
4

1 回答 1

3

Bash 真的不是一种函数式编程语言。首先,函数不是一流的对象。你不能传递一个函数。您可以传递函数的名称,但这只是一个名称;如果名称被赋予一个新值,那么旧值就会丢失。

Bash 没有词法作用域:bash 作用域是动态的。该local命令是一个命令,就像任何其他命令一样。它不是句法。如果未执行,则名称不会成为本地名称。例如:

f() {
  if [[ $1 == local ]]; then local myvar=local; fi
  myvar=changed
}

$ var=original
$ f local
$ echo $myvar
original
$ f global
$ echo $myvar
changed

并且 bash 没有闭包。你可以在函数内部定义一个函数,但是这样定义的函数不带有它的作用域。

$ g() {
>   local myvar=inner
>    f() { echo $myvar; }
>    f
> }
$ myvar=outer
$ g
inner
$ f
outer
$ h() { local myvar=inside_h; f; }
$ h
inside_h
$ f
outer
于 2015-10-10T04:33:01.503 回答