Skip to content

Commit 91fb509

Browse files
Ch06: Add question about using sudo for redirection (#105)
1 parent c51086c commit 91fb509

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

docs/Ch06/index.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -977,6 +977,16 @@ Bash shell 本身提供了调试方法:
977977

978978
`echo < file` 会输出什么?
979979

980+
!!! question "使用 sudo 重定向输出"
981+
982+
当需要将输出重定向到仅 root 用户可写入的文件时,很多人的第一反应是:
983+
984+
```shell
985+
sudo command > output_file
986+
```
987+
988+
但最终失败了。尝试解释这样做不可行的原因。
989+
980990
!!! question "设定 HTTP 请求头"
981991

982992
尝试查询 `curl` 和 `wget` 的文档,给出设定 HTTP 请求头的方法。

docs/Ch06/solution.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,20 @@ icon: material/tooltip-question
2222

2323
而 `echo` 只输出了空行,因为 `echo` 不从标准输入读取内容(它的输入从参数读取)。
2424

25+
## 使用 sudo 重定向输出
26+
27+
??? info "解答"
28+
29+
如果尝试用 `sudo` 将输出重定向到仅 root 用户可写入的文件,会看到 Permission denied 的错误。
30+
31+
这是因为重定向符号 `>` 仍由当前 shell 处理,当前 shell 以普通用户权限运行,没有写入权限。
32+
33+
正确做法是使用 sudo 执行 `tee` 命令,配合管道进行重定向:
34+
35+
```shell
36+
command | sudo tee output_file
37+
```
38+
2539
## 设定 HTTP 请求头
2640

2741
??? info "解答"

0 commit comments

Comments
 (0)