Colored text to the console

219 Views Asked by At

How can I echo colored text to the console?

In Powershell I can do this:

write-host _info_ -fore Yellow -Back Blue

write-host _error_ -fore Yellow -Back Red

write-host _warning_ -fore White -Back DarkYellow

write-host _succes_ -fore Yellow -Back Green

write-host verde -fore Yellow -Back Green -nonewline ; write-host blanco -fore black -back white -nonewline ; write-host rojo -fore yellow -back red

How can I do the same with nushell?

enter image description here

Thanks in advance.

I have not found this information in your documentation.

1

There are 1 best solutions below

0
Darren On

There are a few ways to do this. You've already discovered the ansi command but you can also just do it with escapes and interpolated strings.

Here's an example using the ansi command with interpolation using $""

echo $"(ansi red)Nushell(ansi reset)"

Now to see what's going on "under the hood" you can run this command.

echo $"(ansi red)Nushell(ansi reset)" | debug -r

Which results in something like this.

String {
    val: "\u{1b}[31mNushell\u{1b}[0m",
    span: Span {
        start: 277827,
        end: 277859,
    },
}

Now it's a little easier to see that there are ansi escapes making all this happen. So, that means we can do something like this with the same result.

echo "\e[31mNushell\e[0m"

The key here is that, in nushell, double quotes mean to translate escapes. If you were to use single quotes or backtick quotes, you'd just get a string instead of a red string.