How to redirect stdout+stderr to one file while keeping streams separate?

后端 未结 5 1760
臣服心动
臣服心动 2020-12-28 19:39

Redirecting stdout+stderr such that both get written to a file while still outputting to stdout is simple enough:

cmd 2>&1 | tee output_file
         


        
5条回答
  •  隐瞒了意图╮
    2020-12-28 20:05

    Order can indeed be preserved. Here's an example which captures the standard output and error, in the order in which they are generated, to a logfile, while displaying only the standard error on any terminal screen you like. Tweak to suit your needs.

    1.Open two windows (shells)

    2.Create some test files

    touch /tmp/foo /tmp/foo1 /tmp/foo2
    

    3.In window1:

    mkfifo /tmp/fifo
    /tmp/logfile
    

    4.Then, in window2:

    (ls -l /tmp/foo /tmp/nofile /tmp/foo1 /tmp/nofile /tmp/nofile; echo successful test; ls /tmp/nofile1111) 2>&1 1>/tmp/fifo | tee /tmp/fifo 1>/dev/pts/1
    

    Where /dev/pts/1 can be whatever terminal display you want. The subshell runs some "ls" and "echo" commands in sequence, some succeed (providing stdout) and some fail (providing stderr) in order to generate a mingled stream of output and error messages, so that you can verify the correct ordering in the log file.

提交回复
热议问题