且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

运行shell命令并将输出发送到文件?

更新时间:2023-11-27 14:12:46

运行时

sudo command > file

仅命令以sudo运行,而不是重定向.

Only the command is run as sudo, not redirection.

正如您所指出的,sudo sh -c "command > file"将起作用.但是除非您真的想以身份运行command,否则不要这样做.您只能将重定向部分作为sudo运行. rici的答案涵盖了两种实现方法.这是另一种方法:

As you pointed out, sudo sh -c "command > file" would work. But unless, you really want to run the command as sudo, you should not do it. You can run only redirection part as sudo. The answer by rici covers 2 methods to do it. Here is another method:

command | sudo tee filename >/dev/null #to overwrite (command > file)
command | sudo tee -a filename >/dev/null # to append (command >> file)