• Linux bash 中,如何将正常信息和错误信息输出到文件


    问题描述:

    $ command 2>> error

    $ command 1>> output

    是否有方法,在bash同一行,实现输出stderr到error文件,输出stdout到output文件?

    也就是,如何在bash的同一行,实现stderr和stdout重定向到不同的文件?

    解决方法:

    将它们放入同一行,command 2>> error 1>> output

    然而,注意 >> 是如果文件有数据,会在文件尾部添加内容。而 > 将会重写文件中已经存在的数据。

    只是为了完成目的,你可以写 1> 为 > , 因为其默认的文件描述符是输出。所以1> 和 > 是同样的东西。

    所以,

    command 2> error 1> output 成为 command 2> error > output

    command 2>> error 1>> output 成为 command 2>> error >> output

     

    或者如果你想要把输出(stdout & stderr)混合到同一个文件,可以使用命令:

    command > merged-output.txt 2>&1

    更简单的用法:command &> merged-output.txt

    其中

    2>&1 表示 stderr(文件描述为2) 重定位到stdout(文件描述符为1),也就是标准错误信息发送到与标准输出信息的相同位置。

    补充说明:

    在bash中,0, 1, 2...9 是文件描述符。0代表stdin,1代表stdout,2代表stderror。3~9未使用,可用于其他临时用法。

    任何文件描述符能通过使用操作符符 > 或 >>(append) ,重定向为其他文件描述符或文件。

    用法:<file_descriptor> > <filename | &file_descriptor>

    更多内容,请参考

    http://www.tldp.org/LDP/abs/html/io-redirection.html

     

    技巧:

    Linux make时,可能会出现很多调试信息,若出现错误,由于输出信息过多,在bash下,无法查找到第一个出错的位置的错误信息。此时,就可以采取上面的方法,先将其输出到文件,然后,在文件中,查找第一个出错信息的位置。

    参考资料:

    1、How to redirect stderr and stdout to different files in the same line of bash?

    http://stackoverflow.com/questions/7901517/how-to-redirect-stderr-and-stdout-to-different-files-in-the-same-line-of-bash

  • 相关阅读:
    python深浅拷贝
    软件开发目录规范
    编码规范
    python进程、线程、协程的介绍及使用
    soket粘包问题及解决方案
    python socket通信
    数据开发_机器学习
    数据开发_开发工具以及工具链
    数据开发_Python读取文件
    数据开发_Java设计模式_IO以及读取资源文件
  • 原文地址:https://www.cnblogs.com/klchang/p/4835068.html
Copyright © 2020-2023  润新知