Bash set +x 而不打印

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13195655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:54:23  来源:igfitidea点击:

Bash set +x without it being printed

bashshell

提问by Andreas Spindler

Does anyone know if we can say set +xin bash without it being printed:

有谁知道我们是否可以set +x在不打印的情况下用 bash说:

set -x
command
set +x

traces

痕迹

+ command
+ set +x

but it should just print

但它应该只是打印

+ command

Bash is Version 4.1.10(4). This is bugging me for some time now - output is cluttered with useless set +xlines, making the trace facility not as useful as it could be.

Bash 是版本 4.1.10(4)。这让我困扰了一段时间 - 输出中充斥着无用的set +x线条,使跟踪工具变得不那么有用。

回答by McJoey

I had the same problem, and I was able to find a solution that doesn't use a subshell:

我遇到了同样的问题,我找到了一个不使用子shell的解决方案:

set -x
command
{ set +x; } 2>/dev/null

回答by choroba

You can use a subshell. Upon exiting the subshell, the setting to xwill be lost:

您可以使用子shell。退出子shell后,设置x将丢失:

( set -x ; command )

回答by user108471

I hacked up a solution to this just recently when I became annoyed with it:

最近,当我对此感到恼火时,我想出了一个解决方案:

shopt -s expand_aliases
_xtrace() {
    case  in
        on) set -x ;;
        off) set +x ;;
    esac
}
alias xtrace='{ _xtrace $(cat); } 2>/dev/null <<<'

This allows you to enable and disable xtrace as in the following, where I'm logging how the arguments are assigned to variables:

这允许您启用和禁用 xtrace,如下所示,我正在记录参数如何分配给变量:

xtrace on
ARG1=
ARG2=
xtrace off

And you get output that looks like:

你会得到如下输出:

$ ./script.sh one two
+ ARG1=one
+ ARG2=two

回答by Oliver

How about a solution based on a simplified version of @user108471:

基于@user108471的简化版本的解决方案怎么样:

shopt -s expand_aliases
alias trace_on='set -x'
alias trace_off='{ set +x; } 2>/dev/null'

trace_on
...stuff...
trace_off

回答by user3286792

This is a combination of a few ideas that can enclose a block of code and preserves the exit status.

这是几个想法的组合,可以包含一个代码块并保留退出状态。

#!/bin/bash
shopt -s expand_aliases
alias trace_on='set -x'
alias trace_off='{ PREV_STATUS=$? ; set +x; } 2>/dev/null; (exit $PREV_STATUS)'

trace_on
echo hello
trace_off
echo "status: $?"

trace_on
(exit 56)
trace_off

When executed:

执行时:

$ ./test.sh 
+ echo hello
hello
status: 0
+ exit 56
status: 56