【问题标题】:Bash how to pass environment for a command within script [closed]Bash如何在脚本中为命令传递环境[关闭]
【发布时间】:2021-01-29 15:05:21
【问题描述】:

所以我有一个 python 脚本需要在环境变量中定义语言环境,如下所示:export LC_ALL=C.UTF-8。所以我想我会简单地创建一个如下所示的脚本:

#!/bin/bash
export LC_ALL=C.UTF-8   
sudo python3 example.py

但是python脚本抱怨环境变量设置不正确。当我在执行脚本之前手动运行这些命令或导出环境变量时,程序可以工作。这里一定有什么我遗漏的问题。

【问题讨论】:

标签: python bash environment-variables


【解决方案1】:

好吧,理论上你做对了: 标有export 的环境变量将被导出到子进程(即:从此shell 启动的程序)。

但是。

sudo 有点不同,因为它对安全性非常敏感。 毕竟,如果您使用了正确的变量,您可以完全更改以超级用户权限运行的命令的行为(想想LD_PRELOAD)。

因此sudo 主动阻止将环境变量传递给 sudoed 进程。

幸运的是(对您而言),您可以更改保留哪些环境变量(至少,如果系统的安全策略允许的话)。

来自man 8 sudo

     -E, --preserve-env
                 Indicates to the security policy that the user wishes to preserve
                 their existing environment variables.  The security policy may
                 return an error if the user does not have permission to preserve
                 the environment.

     --preserve-env=list
                 Indicates to the security policy that the user wishes to add the
                 comma-separated list of environment variables to those preserved
                 from the user's environment.  The security policy may return an
                 error if the user does not have permission to preserve the
                 environment.  This option may be specified multiple times.

【讨论】:

  • 所以如果我只对这个 LC_ALL 值感兴趣,那么sudo --preserve-env=LC_ALL python3 example.py 应该足够了吗?
  • 是的。 (但真的很容易尝试一下)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-29
  • 2021-02-28
  • 2012-10-21
  • 1970-01-01
  • 2017-07-22
相关资源
最近更新 更多