bash: escape individual lines from `-x` echoing
xtrace
output goes to stderr, so you could redirect stderr
to /dev/null
:
i_know_what_this_does() {
echo do stuff
} 2> /dev/null
If you still want to see the errors from the commands run inside the functions, you could do
i_know_what_this_does() (
{ set +x; } 2> /dev/null # silently disable xtrace
echo do stuff
)
Note the use of (...)
instead of {...}
to provide a local scope for that function via a subshell. bash
, since version 4.4 now supports local -
like in the Almquist shell to make options local to the function (similar to set -o localoptions
in zsh
), so you could avoid the subshell by doing:
i_know_what_this_does() {
{ local -; set +x; } 2> /dev/null # silently disable xtrace
echo do stuff
}
An alternative for bash
4.0 to 4.3 would be to use the $BASH_XTRACEFD
variable and have a dedicated file descriptor open on /dev/null
for that:
exec 9> /dev/null
set -x
i_know_what_this_does() {
{ local BASH_XTRACEFD=9; } 2> /dev/null # silently disable xtrace
echo do stuff
}
Since bash
lacks the ability to mark a fd with the close-on-exec flag, that has the side effect of leaking that fd to other commands though.
See also this locvar.sh which contains a few functions to implement local scope for variables and functions in POSIX scripts and also provides with trace_fn
and untrace_fn
functions to make them xtraced or not.
The reason that set +x
is printed is that set -x
means "print the command you are about to run, with expansions, before running it. So the shell doesn't know that you want it to not print things until after it has printed the line telling it not to print things. To the best of my knowledge, there's no way of stopping that from happening.