将 stdout 和 stderr 重定向到文件,将 stderr 重定向到屏幕,同时保留输出顺序
redirect stdout and stderr to file and stderr to screen while preserving output order
我想在保留输出顺序的同时将 stdout 和 stderr 重定向到一个文件,然后在屏幕上显示 stderr。看到很多问题讨论一下:
- https://unix.stackexchange.com/questions/9646/show-only-stderr-on-screen-but-write-both-stdout-and-stderr-to-file
- https://unix.stackexchange.com/questions/333198/bash-redirect-stderr-to-file-and-stdout-stderr-to-screen
- https://unix.stackexchange.com/questions/364166/redirect-bash-stdoutstderr-to-one-file-and-stderr-to-another-file
- Write STDOUT & STDERR to a logfile, also write STDERR to screen
但其中 none 似乎按照我的意愿行事或保留顺序。
我的测试脚本:
#!/bin/bash
echo "1: good" >&1
echo "2: error" >&2
echo "3: error" >&2
echo "4: good" >&1
echo "5: error" >&2
echo "6: good" >&1
echo "7: error" >&2
echo "8: good" >&1
echo "9: error" >&2
我目前拥有的:
$ ./test.sh 2>&1 > output.log
标准 UNIX 语义不允许这样做; 不能仅使用内置于bash或POSIX.
中指定的设施可靠地完成
只有当写入发生在同一目的地时,写入才具有相对于彼此的保证顺序。只要您将 stdout 和 stderr 重定向到不同的目的地,操作系统就不再保证对它们执行的写入顺序;当这些写入是到一个单独的进程(例如 tee
)时,该进程必须读取内容并执行其自己的进一步写入,服从 OS 级调度。
可以使用您的操作系统提供(或可用于)的系统调用级跟踪工具来生成系统调用的绝对排序,从而生成明确排序的输出; .
的答案中给出了这方面的示例
然而,使用 bash 本身,您只能控制子进程的文件描述符的连接位置,而不能控制写入这些描述符的内容如何缓冲和刷新,因此根本没有足够的控制来无需重新排序即可实现您的要求。
我想在保留输出顺序的同时将 stdout 和 stderr 重定向到一个文件,然后在屏幕上显示 stderr。看到很多问题讨论一下:
- https://unix.stackexchange.com/questions/9646/show-only-stderr-on-screen-but-write-both-stdout-and-stderr-to-file
- https://unix.stackexchange.com/questions/333198/bash-redirect-stderr-to-file-and-stdout-stderr-to-screen
- https://unix.stackexchange.com/questions/364166/redirect-bash-stdoutstderr-to-one-file-and-stderr-to-another-file
- Write STDOUT & STDERR to a logfile, also write STDERR to screen
但其中 none 似乎按照我的意愿行事或保留顺序。
我的测试脚本:
#!/bin/bash
echo "1: good" >&1
echo "2: error" >&2
echo "3: error" >&2
echo "4: good" >&1
echo "5: error" >&2
echo "6: good" >&1
echo "7: error" >&2
echo "8: good" >&1
echo "9: error" >&2
我目前拥有的:
$ ./test.sh 2>&1 > output.log
标准 UNIX 语义不允许这样做; 不能仅使用内置于bash或POSIX.
中指定的设施可靠地完成只有当写入发生在同一目的地时,写入才具有相对于彼此的保证顺序。只要您将 stdout 和 stderr 重定向到不同的目的地,操作系统就不再保证对它们执行的写入顺序;当这些写入是到一个单独的进程(例如 tee
)时,该进程必须读取内容并执行其自己的进一步写入,服从 OS 级调度。
可以使用您的操作系统提供(或可用于)的系统调用级跟踪工具来生成系统调用的绝对排序,从而生成明确排序的输出;
然而,使用 bash 本身,您只能控制子进程的文件描述符的连接位置,而不能控制写入这些描述符的内容如何缓冲和刷新,因此根本没有足够的控制来无需重新排序即可实现您的要求。