When making complex bash scripts, I will often use the command:
set -x
to enable me to debug the script if it is not behaving.
However I have some UI functions that generate a LOT of garbage in debug mode, so I would like to wrap them in a conditional along the lines of:
ui~title(){
DEBUG_MODE=0
if [ set -x is enabled ] # this is the bit I don't know how to do
then
# disable debugging mode for this function as it is not required and generates a lot of noise
set +x
DEBUG_MODE=1
fi
# my UI code goes here
if [ "1" == "$DEBUG_MODE" ]
then
# re enable debugging mode here
set -x
fi
}
The problem is that I can't figure out how to know if debug mode is enabled or not.
I'm assuming it is possible, I just can't seem to find it despite lots of searching.
Thanks in advance for any tips
Use of set builtin command Bash shell offers debugging options which can be turn on or off using the set command: set -x : Display commands and their arguments as they are executed.
Bash provides extensive debugging features. The most common is to start up the subshell with the -x option, which will run the entire script in debug mode. Traces of each command plus its arguments are printed to standard output after the commands have been expanded but before they are executed.
The set -x command is used to debug bash script where every executed statement is printed to the shell for debugging or troubleshooting purposes. The set -x command can be directly executed in an interactive bash shell or can be used inside the bash script.
The debugging options available in the Bash shell can be switched on and off in multiple ways. Within scripts, we can either use the set command or add an option to the shebang line. However, another approach is to explicitly specify the debugging options in the command-line while executing the script.
Use the following:
if [[ "$-" == *x* ]]; then
echo "is set"
else
echo "is not set"
fi
From 3.2.5. Special parameters:
A hyphen expands to the current option flags as specified upon invocation, by the set built-in command, or those set by the shell itself (such as the -i).
$ [ -o xtrace ] ; echo $?
1
$ set -x
++ ...
$ [ -o xtrace ] ; echo $?
+ '[' -o xtrace ']'
+ echo 0
0
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