TWi*_*Rob 19 bash io-redirection files
我知道如何重定向到一个文件,并使用 tee;在基本层面上。所以
$ alias outanderr='bash -c "echo stdout >&1; echo stderr >&2"'
# A fake "application" displaying both output and error messages.
$ outanderr 1>file # redirect stdout to a file, display stderr
stderr
$ outanderr 2>file # redirect stderr to a file, display stdout
stdout
$ outanderr 1>file 2>&1 # redirect both to a file, display nothing
$ outanderr | tee file; echo "-- file contents --" && cat file
# redirect stdout to a file, display both (note: order is messed up)
stderr
stdout
-- file contents --
stdout
$ outanderr 2>&1 | tee file; echo "-- file contents --" && cat file
# redirect both to a file, display both
stdout
stderr
-- file contents --
stdout
stderr
Run Code Online (Sandbox Code Playgroud)
问题是:写什么来代替问号以获得以下输出:
$ outanderr ???; echo "-- file contents --" && cat file
# redirect both to a file, display stderr
stderr
-- file contents --
stdout
stderr
Run Code Online (Sandbox Code Playgroud)
内容:
Hau*_*ing 13
2>&1 >>outputfile | tee --append outputfile
Run Code Online (Sandbox Code Playgroud)
为方便测试:
echo -n >outputfile; bash -c "echo stdout >&1; echo stderr >&2" 2>&1 >>outputfile |
tee --append outputfile; echo "outputfile:"; cat outputfile
Run Code Online (Sandbox Code Playgroud)
编辑1:
这通过将 stdout (仅)写入文件,使 sterr stdout 使其通过管道,并让 tee 将其输出写入同一文件来工作。
两次写入都必须以追加模式(>>而不是>)完成,否则两者都会覆盖彼此的输出。
由于管道是缓冲区,因此无法保证输出以正确的顺序出现在文件中。如果应用程序连接到两个文件描述符(两个管道),这甚至不会改变。为了保证顺序,两个输出都必须通过相同的通道并分别进行标记。或者你需要一些非常花哨的东西:
/dev/null. 应用程序的输出将通过运行它来分离strace -f -s 32000 -e trace=write。在这种情况下,您必须反转转义。不用说,应用程序不会因为被跟踪而运行得更快。