我如何确保使用 sudo 时设置了环境变量?

我如何确保使用 sudo 时设置了环境变量?

我如何确保环境变量(GRAILS_HOME例如)已设置sudo

我在我的脚本中放入了/etc/profile.d此值并使其生效ugo+x。我需要做什么才能使超级用户看到它?

答案1

尝试

sudo su -

加载-所有环境文件。来自man su

-, -l, --login
   Provide an environment similar to what the user would expect had
   the user logged in directly.

   When - is used, it must be specified as the last su option. The
   other forms (-l and --login) do not have this restriction.

更新:一般情况下,您可以运行sudo -i mycomment,正如手册页sudo所述,

-i [command]
           The -i (simulate initial login) option runs the shell
           specified in the passwd(5) entry of the target user as a
           login shell.  This means that login-specific resource files
           such as .profile or .login will be read by the shell.  If a
           command is specified, it is passed to the shell for
           execution.  Otherwise, an interactive shell is executed.
           sudo attempts to change to that user's home directory
           before running the shell.  It also initializes the
           environment, leaving DISPLAY and TERM unchanged, setting
           HOME, SHELL, USER, LOGNAME, and PATH, as well as the
           contents of /etc/environment on Linux and AIX systems.  All
           other environment variables are removed.

答案2

根据这个答案:设置 PATH 以使其适用于所有用户,包括 root/sudo 如果您注意到 Sudo 默认重置所有变量和路径。

相关部分:

手册页指出sudoers

env_reset       If set, sudo will reset the environment to only contain
                   the LOGNAME, MAIL, SHELL, USER, USERNAME and the SUDO_*
                   variables.  Any variables in the caller's environment
                   that match the env_keep and env_check lists are then
                   added.  The default contents of the env_keep and
                   env_check lists are displayed when sudo is run by root
                   with the -V option.  If the secure_path option is set,
                   its value will be used for the PATH environment
                   variable.  This flag is on by default.

因此,您可以在使用 sudo 时执行以下操作来维护变量

sudo visudo

这将为您打开 sudo 设置。然后按照我所做的操作,在下面添加以下内容

Defaults secure_path="blah"

Defaults env_keep +="VARIABLE VARIABLE VARIABLE"

(不包括由 secure_path 设置的 PATH)并且如果您希望维护多个变量,则这些只是每个变量之间的单个空格。

它的作用是告诉 sudo 保留哪些环境变量而不是忽略哪些环境变量。

完成后,按住 ctrl 并按 o 进行写出,按 Enter 并说“是”进行保存 [即使它指定了一个 tmp 文件,这也没关系,它将被写回到主配置,当询问是否要覆盖时只需说“是”]。

这应该允许您维护您想要的任何变量(一个重要的变量是JAVA_HOME,如果您使用代理,还有http_proxy)。

因此它应该看起来类似于下面,包括您指定的变量:

Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin/bin"
Defaults        env_keep +="GRAILS_HOME"

并验证是否需要退出所有打开的终端窗口并重新打开一个并运行

echo $GRAILS_HOME 

它应该是你设置的,现在发出

sudo echo $GRAILS_HOME

现在应该保持不变

相关内容