首页·终端命令

sudo

权限与归属

用法

sudo [cmd]

以别的用户(默认 root)身份跑一条命令;sudo cmd > file 里的 > 是你自己的 shell 打开的,所以对 root 拥有的文件会失败,那时要用 tee。

常用选项

选项含义
-uRun as another user instead of root
-iStart a login shell with that user environment
-sStart a shell but keep your own environment
-EKeep your environment variables, if the policy allows it
-kForget the cached password right now
-lList what you are allowed to run
-vRefresh the timestamp without running anything

示例

sudo -u postgres psql

Runs the client as the postgres user.

sudo -i

A root login shell, with root PATH and environment.

echo text | sudo tee -a /etc/hosts

Redirection needs tee, because > runs as you.

数字模式和符号模式说的是同一件事:755 和 u=rwx,go=rx 是同一个权限。

怎么看

  • 方括号 [ ] 表示这部分可以不写。
  • 省略号 … 表示可以写多个。
  • 选项区分大小写——有些命令里 -r 和 -R 不是一回事。

常见问题

Q. sudo 是做什么的?

以别的用户(默认 root)身份跑一条命令;sudo cmd > file 里的 > 是你自己的 shell 打开的,所以对 root 拥有的文件会失败,那时要用 tee。

Q. 怎么写?

sudo [cmd] —— 方括号表示可以省略的部分。

Q. 值得记的选项有几个?

这里列了 7 个,完整列表在 man sudo。这条命令属于权限与归属。

相关命令

man 手册: man sudo