将stdout的COPY重定向到bash脚本本身的日志文件

将stdout的COPY重定向到bash脚本本身的日志文件

我知道如何将stdout重定向到文件:

exec > foo.log
echo test

这会将'test'放入foo.log文件中。

现在我想将输出重定向到日志文件并将其保存在stdout上

即它可以从脚本外部轻松完成:

script | tee foo.log

但我想在脚本本身内声明它

我试过了

exec | tee foo.log

但它不起作用。


函数式编程
浏览 591回答 3
3回答

慕莱坞森

busybox,macOS bash和非bash shell的解决方案接受的答案肯定是bash的最佳选择。我在没有访问bash的Busybox环境中工作,并且它不理解exec > >(tee log.txt)语法。它也无法exec >$PIPE正常工作,尝试创建一个与命名管道同名的普通文件,该文件失败并挂起。希望这对没有bash的其他人有用。此外,对于使用命名管道的任何人来说,它是安全的rm $PIPE,因为它取消了管道与VFS的链接,但使用它的进程仍然保持引用计数,直到它们完成。注意$ *的使用不一定安全。#!/bin/shif [ "$SELF_LOGGING" != "1" ]then&nbsp; &nbsp; # The parent process will enter this branch and set up logging&nbsp; &nbsp; # Create a named piped for logging the child's output&nbsp; &nbsp; PIPE=tmp.fifo&nbsp; &nbsp; mkfifo $PIPE&nbsp; &nbsp; # Launch the child process with stdout redirected to the named pipe&nbsp; &nbsp; SELF_LOGGING=1 sh $0 $* >$PIPE &&nbsp; &nbsp; # Save PID of child process&nbsp; &nbsp; PID=$!&nbsp; &nbsp; # Launch tee in a separate process&nbsp; &nbsp; tee logfile <$PIPE &&nbsp; &nbsp; # Unlink $PIPE because the parent process no longer needs it&nbsp; &nbsp; rm $PIPE&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; # Wait for child process, which is running the rest of this script&nbsp; &nbsp; wait $PID&nbsp; &nbsp; # Return the error code from the child process&nbsp; &nbsp; exit $?fi# The rest of the script goes here
打开App,查看更多内容
随时随地看视频慕课网APP