Bash – Inline debug (xtrace) in scripts

bashdebuggingshell-script

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 ?

Best Answer

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).