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.
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).
A portable way to do this (without bugs like [[ ]] ) would be
[[ ]]
case $- in (*x*) echo "under set -x" esac
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
set -x
Find xtrace in $SHELLOPTS .
xtrace
$SHELLOPTS
For instance:
if grep -q xtrace <<<"$SHELLOPTS"; then DO_SOMETHING; fi