有一个具有陷阱的shell函数。调用该函数并输出管道时,陷阱不起作用。是什么原因。
#!/bin/bash
cleanup () {
echo "====> Calling cleanup"
}
_main () {
echo "Starting"
trap 'cleanup' 0
echo "Completed"
}
_main | cat
如果管道被移除,它会按预期工作。
_main
用管道输出
sh -x tp.sh
+ _main
+ echo Starting
+ trap cleanup 0
+ echo Completed
+ cat
Starting
Completed
无管道输出
$ sh -x tp.sh
+ _main
+ echo Starting
Starting
+ trap cleanup 0
+ echo Completed
Completed
+ cleanup
+ echo '====> Calling cleanup'
====> Calling cleanup