reset_x=false if [ -o xtrace ]; then set +x reset_x=true fi # do stuff if "$reset_x"; then set -x fi
You test the shell option with the -o test (using [ as above or with test -o ). If the xtrace ( set -x ) option is set -x , set -x it and set the flag for future use.
In a function, you could even set a RETURN trap to reset when the function returns:
foo () { if [ -o xtrace ]; then set +x trap 'set -x' RETURN fi
Kusalananda
source share