在Linux上使用Bash将所有输出重定向到文件?

时间:2013-05-30 17:03:42

标签: linux bash stdout stderr

我正在尝试将命令行程序的所有输出重定向到文件。我正在使用Bash。一些输出被定向到文件,但是一些仍然出现在终端中并且不存储到文件中。

此处描述了类似的症状:

Redirect all output to file

但是我已经尝试了建议的解决方案(捕获stderr)但没有成功:

<cmd> <args> > stdout.txt 2> stderr.txt

文件stderr.txt已创建,但为空。

可能的线索是命令行程序是与同一台机器上的服务器通信的客户端。可能有些输出来自服务器

有没有办法捕获终端的所有输出,无论其来源如何?

修改

我已确认缺少的输出是由服务器生成的。在单独的终端中运行命令会在两个终端中产生一些输出,我可以将命令终端的所有输出传输到文件。这引发了有关如何捕获服务器输出的问题,但这是一个不同的问题。

6 个答案:

答案 0 :(得分:95)

您可以使用此语法将所有输出stderr和stdout重定向到stdout.txt

<cmd> <args> > allout.txt 2>&1 

答案 1 :(得分:54)

如果服务器是在同一个终端上启动的,那么它就是服务器的stderr,可能是写入终端并且你没有捕获它。

捕获所有内容的最佳方法是运行:

script output.txt

在启动服务器或客户端之前。这将启动一个新的shell,所有终端输出都重定向输出output.txt以及终端。然后从该新shell中启动服务器,然后启动客户端。您在屏幕上看到的所有内容(您的输入和从该shell中写入终端的所有内容的输出)都将写入该文件。

完成后,键入“exit”退出script命令运行的shell。

答案 2 :(得分:48)

虽然不是POSIX,但bash 4有&>运算符:

command &> alloutput.txt

答案 3 :(得分:3)

I had trouble with a crashing program *cough PHP cough* Upon crash the shell it was ran in reports the crash reason, Segmentation fault (core dumped)

To avoid this output not getting logged, the command can be run in a subshell that will capture and direct these kind of output:

sh -c 'your_command' > your_stdout.log 2> your_stderr.err
# or
sh -c 'your_command' > your_stdout.log 2>&1

答案 4 :(得分:3)

您可以执行子shell并重定向所有输出,同时仍将进程置于后台:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

答案 5 :(得分:2)

正确的答案在这里:http://scratching.psybermonkey.net/2011/02/ssh-how-to-pipe-output-from-local-to.html

your_command | ssh username@server "cat > filename.txt"