Bash set +x without it being printed

后端 未结 5 1312
轻奢々
轻奢々 2020-12-07 11:56

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

set -x
command
set +x

traces

+ command         


        
5条回答
  •  悲哀的现实
    2020-12-07 12:28

    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
    echo "status: $?"
    

    When executed:

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

提交回复
热议问题