我将如何创建一个文本文件并在 bash 中使用 sudo 权限填充它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42810888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How would I create a text file and fill it with sudo permission in bash
提问by richard_d_sim
I'm trying to create and fill a file in a directory that requires sudo permission.
我正在尝试在需要 sudo 权限的目录中创建和填充文件。
EDIT: It seems that based on tested the suggested similar post.
编辑:似乎基于测试建议的类似帖子。
sudo su -c "echo 'put in file' > file_name"
echo "Some text" | sudo tee /etc/file
will both create a file within the directory that requires sudo permission
都将在需要 sudo 权限的目录中创建一个文件
回答by Charles Duffy
The question has been edited to include a log of the problem being introduced, which includes the command:
该问题已被编辑为包括所引入问题的日志,其中包括以下命令:
# Taken from edited question
$ echo 'hello' > sudo tee /data/hello
In bash (which allows redirection operators at any point in a simple command), this is precisely equivalent to running:
在 bash 中(它允许在简单命令中的任何点使用重定向操作符),这完全等同于运行:
# From question, with redirection moved to end to make actual behavior more readable
echo 'hello' tee /data/hello > sudo
That is, it's creating a file named sudo
in your current directory, not using sudo
to run tee
(in the above, tee
is just an argument to echo
).
也就是说,它正在创建一个在您当前目录中命名sudo
的文件,而不是sudo
用于运行tee
(在上面,tee
只是一个参数echo
)。
What you want, by contrast, is:
相比之下,你想要的是:
# CORRECT: Using a pipe, not a redirection
echo 'hello' | sudo tee /data/hello
with a pipe (|
) rather than a >
.
使用管道 ( |
) 而不是>
.
回答by GreensterRox
Assuming you have the required sudo privileges you could use an editor like vior nano
假设您拥有所需的 sudo 权限,您可以使用vi或nano等编辑器
sudo vi /etc/file
or
或者
sudo nano /etc/file
If you don't have sudo for those programs you can su to root first and then try:
如果你没有这些程序的 sudo 你可以先 su 到 root 然后尝试:
sudo su -
vi /etc/file
or
或者
nano /etc/file
回答by vielmetti
If you want to do it all on one command line, you can make sure that the file exists by running touch(1) on it. E.g.
如果您想在一个命令行上完成所有操作,您可以通过在文件上运行 touch(1) 来确保该文件存在。例如
sudo touch /etc/file && echo "Some text" | sudo tee /etc/file
sudo touch /etc/file && echo "Some text" | sudo tee /etc/file