Question

So, I've identified a behaviour of my bash script that I find weird.

Here is a test script:

echo "start of script"

(

echo "start of subshell"

cat > /tmp/$$ << EOF
trap 'exit 99' SIGINT

echo "sleep 10, hit ctrl+c now"
sleep 10
EOF

chmod +x /tmp/$$
/tmp/$$

echo "end of subshell"

#)
) | tee -a /tmp/$$.log

echo "end of script"

So, as you can see, I use parentheses that create a subshell to easily pipe the output for logging purposes.

Inside this subshell, I run a script that catches the ctrl+c signal and simply exits the script.

So, depending on if I pipe the output of the subshell or not, the behaviour when hitting ctrl+c during the subscript (sleep 10) differs.

With the | tee -a /tmp/$$.log, the output shows:

[/tmp] ./test.sh
start of script
start of subshell
sleep 10, hit ctrl+c now
end of script

Without the pipe and tee, the output shows:

[/tmp] ./test.sh
start of script
start of subshell
sleep 10, hit ctrl+c now
**end of subshell**
end of script

Can somebody please explain this behaviour? Is there a way to make sure the end of the subscript won't be skipped like that with the pipe and tee?

Thanks

Was it helpful?

Solution

Try using tee option "-i".

(
#script
) | tee -i -a /tmp/$$.log
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top