Shell trick: check if set -x
In a shell script, I wanted to manually set +x
, which disables the echo-command before running each command. I didn't want any -x
invocations in the parent scripts to display the crappy logic I was implementing in this one script. But, I also wanted the script to be dot-sourced, so it would set environment variables that will be used later.
So, I first had to learn how to restore the previous value of +/-x
. And then I just grep and use an if statement at the end.
oldx="$( printf %s\\n "$-" | grep -q -e 'x' && echo YES )"
set +x # hide this cruft
# terrible and verbose logic that should never get displayed to a -x invocation
test "${oldx}" = "YES" && set -x
Comments