Daniel Falk Daniel Falk - 1 month ago 9
Bash Question

Fish shell custom function for output text coloring

When using fish shell in a terminal-emulator (such as terminator) together with a command that outputs lots of text it could be useful to get some color coding on the output. I know that a script can add color code information to the output like "grep --color=auto". I guess it's possible to modify the fish terminal to scan through the output and add this in special places?

What I want to do is that the text "error" appearing in the output from any script always is marked red and that "warning" always is marked yellow. Anyone knows if this is possible by introducing function files in the ~/.config/fish/functions dir or similar?

Answer

This is basically a layering violation. Usually the output of external commands does not go back through the shell. It goes directly to the terminal.

Also, anything you do here has the potential to slow output down. (And because of fish issue #1396, this can be rather extreme).

That said, it's possible if you always pipe to a function like this

function colorstuff
    while read -l input
        switch $input
            case "*error*"
                set_color red
                echo $input
            case "*warning*"
                set_color yellow
                echo $input
            case "*"
                set_color normal
                echo $input
        end
    end
    set_color normal
end

Use it like somecommand | colorstuff. (And maybe add ^&1 if you also wish to have stderr colored)

In my tests, this causes a noticeable slowdown, and even with that issue fixed it will still be slower since it has to match every single line.

Really, the real solution is for whatever tool you are using to color itself, since it knows what the output means. All this can do is look for keywords.