Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Bash you can set -x to enable debugging, is there any way to know if that has been set or not from within the script?

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

like image 891
edmondscommerce Avatar asked May 17 '13 09:05

edmondscommerce


People also ask

Which command would enable debugging of a shell script?

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.

Can you debug a bash script?

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.

What is set X in Bash?

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.

Which of the following are valid ways to debug a Bash shell 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.


2 Answers

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).

like image 91
Ortwin Angermeier Avatar answered Nov 22 '22 05:11

Ortwin Angermeier


$ [ -o xtrace ] ; echo $?
1
$ set -x
++ ...
$ [ -o xtrace ] ; echo $?
+ '[' -o xtrace ']'
+ echo 0
0
like image 35
Ignacio Vazquez-Abrams Avatar answered Nov 22 '22 05:11

Ignacio Vazquez-Abrams