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

I would like to temporarily set -x in my script and then return to its original state.

Is there a way to do this without starting a new subshell? Something like

echo_was_on=....... ... ... if $echo_was_on; then set -x; else set +x; fi 
+16
set bash builtin built-in
source share
6 answers

You can check the value of $- to view the current options; if it contains x, it has been installed. You can check it like this:

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

Or in case case

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

Here are the reusable functions based on @ shellter's and @glenn jackman's answers :

 is_shell_attribute_set() { # attribute, like "e" 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 -e if is_shell_attribute_set e; then echo "yes"; else echo "no"; fi # yes set +e if is_shell_attribute_set e; then echo "yes"; else echo "no"; fi # no set -o pipefail if is_shell_option_set pipefail; then echo "yes"; else echo "no"; fi # yes set +o pipefail if is_shell_option_set pipefail; then echo "yes"; else echo "no"; fi # no 

Update : for Bash, test -o is the best way to do the same, see @Kusalananda's answer .

+8
source share
 reset_x=false if [ -o xtrace ]; then set +x reset_x=true fi # do stuff if "$reset_x"; then set -x fi 

You test the shell option with the -o test (using [ as above or with test -o ). If the xtrace ( set -x ) option is set -x , set -x it and set the flag for future use.

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

 foo () { if [ -o xtrace ]; then set +x trap 'set -x' RETURN fi # rest of function body here } 
+6
source share

Also:

 case $(set -o | grep xtrace | cut -f2) in off) do something ;; on) do another thing ;; esac 
+3
source share

less detailed

 [ ${-/x} != ${-} ] && tracing=1 || tracing=0 
+2
source share

All Articles