Colour highlighting output based on regex in shell

后端 未结 8 1929
鱼传尺愫
鱼传尺愫 2020-12-02 07:32

I\'d like to know if I can colour highlight the output of a shell command that matches certain strings.

For example, if I run myCommand, with the output below:

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 08:03

    If you want to enable this globally, you'll want a terminal feature, not a process that you pipe output into, because a pipe would be disruptive to some command (two problems are that stdout and stderr would appear out-of-order and buffered, and that some commands just behave differently when outputting to a terminal).

    I don't know of any “conventional” terminal with this feature. It's easily done in Emacs, in a term buffer: configure font-lock-keywords for term-mode.

    However, you should think carefully whether you really want that feature all the time. What if the command has its own colors (e.g. grep --color, ls --color)? Maybe it would be better to define a short alias to a colorizer command and run myCommand 2>&1|c when you want to colorize myCommand's output. You could also alias some specific always-colorize commands.

    Note that the return status of a pipeline is its last command, so if you run myCommand | c, you'll get the status of c, not myCommand. Here's a bash wrapper that avoids this problem, which you can use as w myCommand:

    w () {
      "$@" | c
      return $PIPESTATUS[0]
    }
    

提交回复
热议问题