Inline debug (xtrace) in scripts

9,950

I'm not aware of any shell that has such an operator. However, with most shells (ksh being the exception) you can silently toggle xtrace with:

{
  case $- in
    (*x*) set +x;;
    (*) set -x
  esac
} 2> /dev/null

So you could make it an alias:

alias 'xx={
  case $- in
    (*x*) set +x;;
    (*) set -x
  esac
} 2> /dev/null'

And use as:

set -x
echo traced
xx; echo not traced; xx
echo traced
set +x

Note that with bash, you need shopt -s expand_aliases for aliases to be expanded in non-interactive shells (like in scripts).

Share:
9,950

Related videos on Youtube

Luciano
Author by

Luciano

Updated on September 18, 2022

Comments

  • Luciano
    Luciano over 1 year

    Is there a way to force enable or disable debug (xtrace) per command line in scripts ?

    In Windows Shell ("ms-dos") is an "@" which can prefix a command line, disabling that line to be showed if the echo (lets say debug) is enabled (echo on).

    Consider xtrace on (set -x), but we could ommit its effect in some lines prefixing it lets say with "@". Like as:

    set -x
    @echo Listing...
    ls
    set +x
    

    Output example:

    Listing...
    + ls
    file1
    file2
    

    Is something similar in shell scripts ?

  • Stéphane Chazelas
    Stéphane Chazelas over 8 years
    @Gilles, (re: edit) indeed pdksh and mksh R50 output + 2> /dev/null, but not R46 here for some reason.