4

With the option set -x, each command is echoed to STDERR before execution, prefixed by the expanded $PS4, with the first character being repeated according to the call stack depth.

I want the output of the $PS4 prompt to be colorized. I.e. where

(set -x; ls -l)

will currently print

+ ls -l

I want an output

\033[90m+ ls -l\033[0m
      \              \
       \              `- Reset color
        `- Muted gray

However, with PS4 being printed before echoing the command, I can't think of a method to reset the color with \033[0m before the command is executed.

Is it possible to do this somehow?

kdb
  • 199
  • 4
  • Consider using a `DEBUG` trap instead of `set -x`. Example: `set -T; trap 'printf "%*s\e[90m+%s\e[m\n" "$((${#FUNCNAME[*]}*2))" "" "$BASH_COMMAND"' DEBUG` –  Oct 14 '19 at 14:26
  • @mosvy While it works, it doesn't come close to the convenience of `set -x` / `bash -x myscript`. Though I can imagine doing something like `setx () { ; }; export -f setx` in `.bashrc`, and using `(setx; debug this)` and `bash -c 'setx; source myscript'`. Using PS4 however would have the advantage, that it can be inherited by scripts without having to change them. – kdb Oct 15 '19 at 10:23
  • I'm sorry you find that so inconvenient. With real scripts (not `-c` or stdin), you can use `export BASH_ENV` to make them execute commands upon start-up. –  Oct 15 '19 at 12:48
  • correction: with newer versions of bash (eg. 5.0.3) `BASH_ENV` will also be sourced by scripts given via `-c` or read from stdin, –  Oct 15 '19 at 17:33

0 Answers0