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

允我心安 提交于 2019-12-03 23:00:55

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
shellter

Or in a case statement

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

Here are re-usable 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 a better way to accomplish the same, see @Kusalananda's answer.

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

# do stuff

if "$reset_x"; then
    set -x
fi

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

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
}

Also:

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

less verbose

[ ${-/x} != ${-} ] && tracing=1 || tracing=0
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!