在bash中,如何获取set -x的当前状态?

问题描述 投票:13回答:6

我想在我的脚本中临时设置-x然后返回到原始状态。

有没有办法在不启动新子shell的情况下执行此操作?就像是

echo_was_on=.......
... ...
if $echo_was_on; then set -x; else set +x; fi
bash set built-in
6个回答
19
投票

你可以查看$-的值来查看当前选项;如果它包含x,则设置为。您可以这样检查:

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

10
投票

或者在案例陈述中

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

8
投票

以下是可重复使用的功能,基于@shellter's@glenn jackman's答案:

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
}

用法示例:

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

更新:对于Bash,test -o是一个更好的方法来实现同样的目标,请参阅@Kusalananda's answer


5
投票
reset_x=0
if [ -o xtrace ]; then
    set +x
    reset_x=1
fi

# do stuff

if [ "$reset_x" -eq 1 ]; then
    set -x
fi

您使用-o测试(使用上面的[或使用test -o)测试shell选项。如果设置了xtrace选项(set -x),则取消设置并设置一个标志供以后使用。

在函数中,您甚至可以设置一个RETURN陷阱来在函数返回时重置设置:

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

    # rest of function body here
}

3
投票

也:

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

2
投票

不那么冗长

[ ${-/x} != ${-} ] && tracing=1 || tracing=0
© www.soinside.com 2019 - 2024. All rights reserved.