I have a function that runs several commands and each of them take awhile to finish. I added set -x at the beginning so that I can see exactly which command is executing while it's running. Then at the end I disable it with set x.
function toolong() {
set -x;
takes_a_long_time &&\
takes_also_a_long_time &&\ # <=== Hangs here, for example
takes_more time
set x;
}
My problem is that sometimes I need to kill my process if one of the functions hangs or is taking too long. When that happens i'm left with a bunch of crap in my shell as set x never got called.
Is there a way to limit the scope of set -x only to the duration of a specific function or otherwise guarantee that set x always gets called?
CodePudding user response:
If you don't need to affect current execution environment, just run it all in a subshell.
toolong() {
(
set -x;
takes_a_long_time &&
takes_also_a_long_time &&
takes_more time
)
}
Or shorter you can:
toolong() (
set -x;
takes_a_long_time &&
takes_also_a_long_time &&
takes_more time
)
CodePudding user response:
You can define a trap for cleaning up when the function is interrupted:
trap '[[ $FUNCNAME == toolong ]] && set x' INT
or systematically when using a CtrlC:
trap 'set x' INT
