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

jms*_*ter 17 bash set built-in

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

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

echo_was_on=.......
... ...
if $echo_was_on; then set -x; else set +x; fi
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 19

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

old_setting=${-//[^x]/}
...
if [[ -n "$old_setting" ]]; then set -x; else set +x; fi
Run Code Online (Sandbox Code Playgroud)


she*_*ter 10

或者在案例陈述中

 case $- in
   *x* ) echo "X is set, do something here" ;;
   * )   echo "x NOT set" ;;
 esac
Run Code Online (Sandbox Code Playgroud)


sko*_*zin 8

这里有可重复使用的功能,基于@ shellter@glenn jackman的答案:

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
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

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
Run Code Online (Sandbox Code Playgroud)

更新:对于Bash来说,这test -o是一个更好的方法,请参阅@ Kusalananda的回答.


Kus*_*nda 6

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

# do stuff

if "$reset_x"; then
    set -x
fi
Run Code Online (Sandbox Code Playgroud)

您可以通过测试来测试shell选项-o[如上所述或与一起使用test -o)。如果xtrace设置了该选项(set -x),请取消设置该选项并设置一个标志以备后用。

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

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

    # rest of function body here
}
Run Code Online (Sandbox Code Playgroud)

  • @skozin`bash`支持它。这个问题专门涉及标题和标签上的“ bash”。 (2认同)