In bash, how to get the current status of set -x?

reset_x=false
if ! [ -o xtrace ]; then
    set -x
    reset_x=true
fi

# do stuff

"$reset_x" && set +x

You test a shell option with the -o test (using [ as above or with test -o). If the xtrace option isn't set (set +x), then set it and set a flag to turn it off later.

In a function, you could even have set a RETURN trap to reset the setting when the function returns:

foo () {
    if ! [ -o xtrace ]; then
        set -x
        trap 'set +x' RETURN
    fi

    # rest of function body here
}

Or in a case statement

 case $- in
   *x* ) echo "X is set, do something here" ;;
   * )   echo "x NOT set" ;;
 esac

You can check the value of $- to see the current options; if it contains an x, it was set. You can check like so:

old_setting=${-//[^x]/}
...
if [[ -n "$old_setting" ]]; then set -x; else set +x; fi

In case it's not familiar to you: the ${} above is a Bash Substring Replacement, which takes the variable - and replaces anything that's not an x with nothing, leaving just the x behind (or nothing, if there was no x)

Tags:

Bash

Set

Built In