bash - 通过 sudo 从另一个 shell 脚本调用 shell 脚本 - 环境变量?

标签 bash shell environment-variables sudo

我正在从脚本 A 调用 bash 脚本 B。在脚本 A(父脚本)中,我正在导出一些变量。我想在脚本 B(下标)中使用这些变量,但是变量值没有从脚本 A 传递到脚本 B。有没有办法从脚本 B 访问变量值?

#!/bin/bash
# script_A.sh
export VAR="value"
enter code here
sudo -u user ./script_B.sh

#!/bin/bash
# script_B.sh
echo $VAR    # this prints nothing

最佳答案

正如@geekosaur 提到的,sudo 出于安全原因重置环境。 要保护环境,请通过 -E 切换到 sudo

来自 sudo 联机帮助页:

-E

The -E (preserve environment) option indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the -E option is specified and the user does not have permission to preserve the environment.

关于bash - 通过 sudo 从另一个 shell 脚本调用 shell 脚本 - 环境变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10098414/

相关文章:

bash - 如何将字符串转换为 Bash 中单个字符的数组?

macos - 如何设置链接以从 OSX 上的终端打开 Visual Studio Code?

regex - 日期的 Shell REGEX

apache - 使用 mod_wsgi 激活 virtualenv 后的环境变量

node.js - ENV 变量未正确添加到容器环境中

BASH:排除 "find"命令中的目录

bash - 在 Bash 中从命令行读取 glob

linux - 打开一个新的终端会产生一个新的 shell 吗?

linux - 在 zsh 中获取进程的 pid

environment-variables - 如何在 docker .env 文件中使用环境变量?