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? 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? bash bash

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?


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 00


Just for the sake of completeness, here are the two re-usable functions:

is_shell_attribute_set() { # attribute, like "x"  case "$-" in    *"$1"*) return 0 ;;    *)    return 1 ;;  esac}is_shell_option_set() { # option, like "pipefail"  case "$(set -o | grep "$1")" in    *on) return 0 ;;    *)   return 1 ;;  esac}

Usage example:

set -xif is_shell_attribute_set e; then echo "yes"; else echo "no"; fi # yesset +xif is_shell_attribute_set e; then echo "yes"; else echo "no"; fi # noset -o pipefailif is_shell_option_set pipefail; then echo "yes"; else echo "no"; fi # noset +o pipefailif is_shell_option_set pipefail; then echo "yes"; else echo "no"; fi # no