sudo -H 做什么?

What does sudo -H do?

尝试使用 pip 安装 virtualenv 后

$ pip install virtualenv

我遇到了权限被拒绝的错误

IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/virtualenv.py'

所以我用sudo来安装virtualenv

$ sudo pip install virtualenv

但随后出现警告:

The directory '/Users/petertao/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/Users/petertao/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

sudo 的 -H 标志有什么作用?

一般

man sudo(确切的文本可能会有所不同,但会相似):

-H

The -H (HOME) option requests that the security policy set the HOME environment variable to the home directory of the target user (root by default) as specified by the password database. Depending on the policy, this may be the default behavior.

那么为什么这甚至是一个选项? 通常使用"sudo"不会改变$HOME环境变量。

例如:

 echo $HOME $USER
/home/testuser testuser

 sudo bash -c 'echo $HOME $USER'
/home/testuser root

 sudo -H bash -c 'echo $HOME $USER'
/home/root root

您可以看到普通的 sudo 将我是哪个用户从 "testuser" 更改为 "root",但不会更改 $HOME 设置的内容,而 sudo -H 也会将变量从 "my" home目录到root的home目录。

你的情况

pip 警告你它是作为用户 root 执行的,并且想要修改 $HOME 中的内容,它被设置为'/Users/petertao',它不属于 root(很可能是 "petertao" 用户)。 该警告表明 pip 使用 $HOME 来缓存文件,但由于文件夹所有权差异而禁用了自己的缓存。

当然,当以 root 身份执行时,pip 可以修改 '/Users/petertao/Library/Caches/pip',因为 root 是(几乎)全能的。 这以后可能会变得很麻烦,因为没有 root 的程序 运行 无法再覆盖或修改这些文件。 相反,pip 拒绝写入另一个用户拥有的目录。

-h 标志通常表示人类可读的格式 它是 Linux OS 中的一种方便的内置转换。例如,如果你在 Linux 中进入你的命令终端,在我的例子中是 raspberry pi 并输入 df。这将显示您已用和可用的内存。它会显示类似您有 448336 字节的内容。你可能喜欢嗯,这令人困惑。现在输入 df -h(使用 -h 标志)你应该得到这样的结果 448M 而不是 4488336 字节。