关于在 Linux shell 中将函数传递给子进程的问题

Hei*_*bug 3 bash shellshock

我正在做 Shellshock 实验室,本教程提供了一种通过环境变量将函数传递给子进程的方法:

$ foo='() { echo "hello"; }'
$ export foo
$ /bin/bash
$ foo
hello
Run Code Online (Sandbox Code Playgroud)

然而,当我在 Ubuntu 20.04 上尝试这个时,foo并没有转换为子进程中的函数。

$ foo='() { echo "hello"; }'
$ export foo
$ /bin/bash
$ foo
Command 'foo' not found, did you mean: ...
Run Code Online (Sandbox Code Playgroud)

有什么我错过的吗,或者这种方法只适用于某些版本的 bash?

Raf*_*ffa 6

在 Bash 中,您可以像这样定义shell 函数:


name () { ...; }
Run Code Online (Sandbox Code Playgroud)

或者像这样:

function name { ...; }
Run Code Online (Sandbox Code Playgroud)

多行的看起来像这样:

name ()
{
...
...
}
Run Code Online (Sandbox Code Playgroud)

或者像这样:

function name
{
...
...
}
Run Code Online (Sandbox Code Playgroud)

并像这样导出-f

export -f name
Run Code Online (Sandbox Code Playgroud)

因此,像这样声明你的函数:

foo () { echo "hello"; }
Run Code Online (Sandbox Code Playgroud)

然后像这样导出:

export -f foo
Run Code Online (Sandbox Code Playgroud)

技术通知

也就是说,您所描述的类似于大约十年前 Bash 中存在的一个历史漏洞(特别是在“函数导出”功能/机制语法和后续解析中),但很久以前就已修复,因此不再适用于 Bash 除非不知怎的,你的系统上一直有一个未打补丁/未更新的 Bash 版本。

请参见: