3 回答

TA貢獻1810條經驗 獲得超4個贊
busybox,macOS bash和非bash shell的解決方案
接受的答案肯定是bash的最佳選擇。我在沒有訪問bash的Busybox環境中工作,并且它不理解exec > >(tee log.txt)語法。它也無法exec >$PIPE正常工作,嘗試創建一個與命名管道同名的普通文件,該文件失敗并掛起。
希望這對沒有bash的其他人有用。
此外,對于使用命名管道的任何人來說,它是安全的rm $PIPE,因為它取消了管道與VFS的鏈接,但使用它的進程仍然保持引用計數,直到它們完成。
注意$ *的使用不一定安全。
#!/bin/sh
if [ "$SELF_LOGGING" != "1" ]
then
# The parent process will enter this branch and set up logging
# Create a named piped for logging the child's output
PIPE=tmp.fifo
mkfifo $PIPE
# Launch the child process with stdout redirected to the named pipe
SELF_LOGGING=1 sh $0 $* >$PIPE &
# Save PID of child process
PID=$!
# Launch tee in a separate process
tee logfile <$PIPE &
# Unlink $PIPE because the parent process no longer needs it
rm $PIPE
# Wait for child process, which is running the rest of this script
wait $PID
# Return the error code from the child process
exit $?
fi
# The rest of the script goes here
添加回答
舉報