目标是制作一个简单的非侵入式包装器,将stdin和stdout跟踪到stderr:
#!/bin/bash
tee /dev/stderr | ./script.sh | tee /dev/stderr
exit ${PIPESTATUS[1]}
Run Code Online (Sandbox Code Playgroud)
测试脚本script.sh:
#!/bin/bash
echo asd
sleep 1
exit 4
Run Code Online (Sandbox Code Playgroud)
但是当脚本退出时,它不会终止包装器.可能的解决方案是tee从管道的第二个命令结束第一个:
#!/bin/bash
# Second subshell will get the PID of the first one through the pipe.
# It will be able to kill the whole script by killing the first subshell.
# Create a temporary named pipe (it's safe, conflicts will throw an error).
pipe=$(mktemp -u)
if ! mkfifo $pipe; then
echo "ERROR: debug tracing pipe creation …Run Code Online (Sandbox Code Playgroud) bash ×1