sudo执行的程序获取到错误的DBUS和env

The program executed by sudo obtains the wrong DBUS and env

我需要用getenv判断系统是X11还是Wayland,DBUS实现截屏功能。 他们在没有 sudo 的情况下工作得很好。 但是,当使用sudo时,getenv得到了错误的值,gdbus无法定位到DBUS。 我很确定这是 sudo 的问题,因为我试过了 echo $WAYLAND_DISPLAYsudo echo $Wayland_DISPLAYd-feetsudo d-feet。当他们不使用 sudo 时,他们是对的。 但是由于程序中其他功能的要求,不得不使用sudo。有什么好办法吗?

Is there any good idea?

默认情况下,sudo 在全新的环境中运行命令。来自 man 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.

您可以列出要保留的变量。

sudo --preserve-env=DBUS_SESSION_BUS_ADDRESS,DISPLAY,WAYLAND_DISPLAY,other_variables,etc command