0

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
    Color formatting is a matter of the terminal that a shell is outputting to. You may find your answer at: https://github.com/nushell/nu-ansi-term (the nushell ANSI terminal) – Paul Dempsey Apr 10 '23 at 20:49
  • Now I found the answer: $'(ansi { fg: y bg: g attr: b }) verde (ansi { fg: b bg: w attr: b }) blanco (ansi { fg: y bg: r attr: b }) rojo' thank you for your help. – Alejandro Bermúdez Apr 11 '23 at 04:18

1 Answers1

0

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.

Darren
  • 483
  • 7
  • 15