在Bash中,你可以使用set -x来启用调试模式,有没有一种方法可以从脚本内部知道是否已经设置了它?

20

当编写复杂的bash脚本时,我经常使用命令:

set -x

为了让我能够调试脚本,以确定它是否表现正常。
但是,我有一些UI函数在调试模式下会产生大量垃圾数据,因此我想要将它们包装在条件语句中,例如:
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
}

问题在于我无法弄清楚如何知道是否启用了调试模式。

我假设这是可能的,但尽管搜索了很多,我似乎找不到答案。

感谢您提供任何提示。


两个很棒的答案,干杯! - edmondscommerce
3个回答

29

请使用以下内容:

if [[ "$-" == *x* ]]; then
  echo "is set"
else
  echo "is not set"
fi

来自3.2.5. 特殊参数

连字符会扩展为当前选项标志,这些标志是在调用时由set内置命令指定的,或者是由shell本身设置的(例如-i)。


1
[ ${-/x/} != $- ] 是另一种获得相同结果的方式:如果从 $- 中移除 x (${-/x/}) 与原始 $- 不同,那么就意味着 x 已经启用。 - Ictus

9
$ [ -o xtrace ] ; echo $?
1
$ set -x
++ ...
$ [ -o xtrace ] ; echo $?
+ '[' -o xtrace ']'
+ echo 0
0

2

为了完整起见,这里是两个可重复使用的函数:

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
}

使用示例:

set -x
if is_shell_attribute_set e; then echo "yes"; else echo "no"; fi # yes

set +x
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 # no

set +o pipefail
if is_shell_option_set pipefail; then echo "yes"; else echo "no"; fi # no

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接