为什么 bash 使用 sudo 无法识别某些用户功能?

san*_*rys 3 command-line bash

初始条件: 我定义了一个函数并将其导出:

myfunction () { echo OK ; }
export -f myfunction
Run Code Online (Sandbox Code Playgroud)

我有一个简单的 bash 文件:test.sh

#!/bin/bash
myfunction
Run Code Online (Sandbox Code Playgroud)

使用当前用户测试 OK: 如果我运行:

bash test.sh
Run Code Online (Sandbox Code Playgroud)

有用 :)

不适用于 sudo : 但是如果我在 sudo 中运行:

sudo bash test.sh
Run Code Online (Sandbox Code Playgroud)

我有错误:

test.sh: ligne2: myfunction : commande introuvable
Run Code Online (Sandbox Code Playgroud)

意思是

test.sh: line2: myfunction : command not found
Run Code Online (Sandbox Code Playgroud)

为什么我的功能在 sudo 中不起作用?它如何在 sudo 中工作?

非常感谢 :)

Flo*_*sch 6

出于安全原因sudo,在运行其子进程之前丢弃 shell 函数和大多数环境变量。

您需要包含myfunctioninto的定义test.sh