Is there a way to check if a shell script is executed with the -x flag

I am trying to verify a script that if this script is executed with the -x flag, which is intended for debugging for shell scripts. Is there any way to check that in the script itself that -x is installed. I want to conditionally test this and do something if it is installed.

+5
source share
4 answers

Using:

if [[ $- == *x* ]]; then echo "debug" else echo "not debug" fi 

From the bash guide :

($ -, hyphen). Expands to the current options flags specified during the call, with the set builtin command or those set by the shell itself (for example, -i).

+10
source

A portable way to do this (without bugs like [[ ]] ) would be

 case $- in (*x*) echo "under set -x" esac 
+2
source

You can capture the DEBUG signal, for example:

 trap "do_this_if_it_is_being_debugged" DEBUG function do_this_if_it_is_being_debugged() { ... } 

Note that this must be done before set -x is executed

+2
source

Find xtrace in $SHELLOPTS .

For instance:

 if grep -q xtrace <<<"$SHELLOPTS"; then DO_SOMETHING; fi 
0
source

All Articles