I am trying to check in the script, that if that script is executed with -x flag which is for the debugging for shell scripts. Is there any way to check that in script itself that -x is set. I want to conditionally check that and do something if that is set.
Use:
if [[ $- == *x* ]]; then
echo "debug"
else
echo "not debug"
fi
From Bash manual:
($-, a hyphen.) Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option).
The portable way to do this (without bashisms like [[ ]]
) would be
case $- in
(*x*) echo "under set -x"
esac
You can trap the DEBUG signal, like so:
trap "do_this_if_it_is_being_debugged" DEBUG
function do_this_if_it_is_being_debugged() {
...
}
Note this needs to be executed before the set -x
is being executed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With