問題描述
我有一個僅包含一行的bash腳本myhome.sh
:
echo $HOME
腳本的所有者是用戶:
$ ls -l myhome.sh
-rw-rw-r-- 1 user user <date> <time> myhome.sh
在Ubuntu 16.04和17.10中,我得到了:
$ echo $HOME
/home/user
$ sudo echo $HOME
/home/user
$ bash myhome.sh
/home/user
$ sudo bash myhome.sh
/home/user
在Debian Buster /Testing中,我得到:
$ echo $HOME
/home/user
$ sudo echo $HOME
/home/user
$ bash myhome.sh
/home/user
# WHY ?
$ sudo bash myhome.sh
/root
我不明白為什麽在Debian腳本中,如果用sudo執行,我總是得到$HOME=/root
而在Ubuntu中卻得到$HOME=/home/user
。有誰知道Ubuntu開發人員做了哪些更改?
最佳方法
Debian和Ubuntu都附帶一個包含Defaults env_reset
的/etc/sudoers
文件,該文件將重置環境變量。
但是,env_reset
的行為從不觸摸$ HOME更改為將其重置為目標用戶的家。
Ubuntu決定修補其版本的sudo
,以保持以前的行為:https://bugs.launchpad.net/ubuntu/+source/sudo/+bug/760140
在Ubuntu中,為了將$ HOME環境變量重置為目標用戶,必須在其/etc/sudoers
中設置Defaults always_set_home
或Defaults set_home
(在這種情況下,隻有sudo -s
會更新HOME)。
Ubuntu跟蹤器中的此錯誤在不設置sudo中的$ HOME時具有更多原理:https://bugs.launchpad.net/ubuntu/+source/sudo/+bug/1373495
參見評論4:
If HOME is removed, then e.g. vim, bash, etc., will use /root/.vimrc, /root/.bashrc, etc rather than the user’s ~/.vimrc, ~/.bashrc, etc. While it’s a bad idea to run X clients via sudo, they too would likely look in the wrong locations for configuration files, and there’s a chance that X11 clients may not even be able to connect to the X11 server if they are aimed at the wrong .Xauthority file.
這是Ubuntu開發人員的明智決定。
此答案具有有關sudoers選項的更多詳細信息,例如always_set_home
:https://unix.stackexchange.com/a/91572/281844
您的問題中還有第二個問題,就是sudo echo $HOME
,即使在Debian中,它仍然顯示用戶的住所。
發生這種情況是因為 shell 程序在運行sudo
命令之前正在擴展$HOME
。
所以這:
$ sudo echo $HOME
首先由shell擴展為:
$ sudo echo /home/user
然後sudo以root身份執行echo /home/user
…
這也應顯示差異:
$ sudo bash -c 'echo $HOME'
/root
或獲得完整的root shell並在此處查看環境變量:
$ sudo -s
# echo $HOME
/root