如何将命令的输出通过管道传输到 Linux 上的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2840187/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:01:44  来源:igfitidea点击:

How to pipe the output of a command to file on Linux

linuxubuntu

提问by morpheous

I am running a task on the CLI, which prompts me for a yes/no input.

我正在 CLI 上运行一个任务,它提示我输入是/否。

After selecting a choice, a large amount of info scrolls by on the screen - including several errors. I want to pipe this output to a file so I can see the errors. A simple '>' is not working since the command expects keyboard input.

选择一个选项后,大量信息在屏幕上滚动 - 包括几个错误。我想将此输出通过管道传输到文件,以便我可以看到错误。简单的“>”不起作用,因为该命令需要键盘输入。

I am running on Ubuntu 9.1.

我在 Ubuntu 9.1 上运行。

回答by Delan Azabani

Use 2>rather than just >.

使用2>而不仅仅是>.

回答by GregMeno

If the program was written by a sane person what you probably want is the stderr not the stdout. You would achieve this by using something like

如果程序是由一个理智的人编写的,您可能想要的是 stderr 而不是 stdout。你可以通过使用类似的东西来实现这一点

foo 2> errors.txt

foo 2> errors.txt

回答by John Kugelman

command &> output.txt

You can use &>to redirect both stdout and stderr to a file. This is shorthand for command > output.txt 2>&1where the 2>&1means "send stderr to the same place as stdout" (stdout is file descriptor 1, stderr is 2).

您可以使用&>将 stdout 和 stderr 重定向到文件。这是速记command > output.txt 2>&1其中2>&1的意思是“发送错误输出到相同的地方标准输出”(stdout是文件描述符1,标准错误是2)。

For interactive commands I usually don't bother saving to a file if I can use lessand read the results right away:

对于交互式命令,如果我可以立即使用less和读取结果,我通常不会费心保存到文件中:

command 2>&1 | less

回答by Epcylon

echo yes | command > output.txt

Depending on how the command reads it's input (some programs discard whatever was on stdin before it displays it's prompt, but most don't), this should work on any sane CLI-environment.

根据命令读取输入的方式(某些程序在显示提示之前丢弃 stdin 上的任何内容,但大多数不会),这应该适用于任何正常的 CLI 环境。

回答by simranjeet

you can use 2> option to send errors to the file.

您可以使用 2> 选项将错误发送到文件。

example:

例子:

command 2> error.txt

命令 2> error.txt

(use of option 2>) --- see if their would be any error while the execution of the command it will send it to the file error.txt.

(使用选项 2>) --- 看看它们是否会在执行命令时出现任何错误,它会将其发送到文件 error.txt。