# 使用sudo在文件中添加内容

在shell命令行中，有时候需要给一个`root`用户的文件添加内容，但是当前shell执行用户是普通用户身份，则会出现如下执行权限不足的报错

```bash
$ echo "export PATH=$PATH:/opt/bin" >> /etc/profile
-bash: /etc/profile: Permission denied
```

解决的方法有以下两种：

* 使用`sudo tee -a`命令，通过管道传递需要添加的内容给`tee`，由于`tee`通过`sudo`执行，就具有权限写入文件

```bash
echo "export PATH=$PATH:/opt/bin" | sudo tee -a /etc/profile
```

* 使用`sudo bash -c`命令，使得整个shell都具有`root`用户权限

```bash
sudo bash -c "echo 'export PATH=$PATH:/opt/bin' >> /etc/profile"
```

## 参考

* [How to append to a file as sudo?](http://superuser.com/questions/136646/how-to-append-to-a-file-as-sudo)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://huataihuang.gitbook.io/cloud-atlas-draft/develop/shell/bash/append_to_file_as_sudo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
