Colored text to the console.

huangapple go评论88阅读模式
英文:

Colored text to the console

问题

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 success -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?

Colored text to the console.

Thanks in advance.

I have not found this information in your documentation.

英文:

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?

Colored text to the console.

Thanks in advance.

I have not found this information in your documentation.

答案1

得分: 1

有几种方法可以实现这一点。您已经发现了ansi命令,但您也可以使用转义和插值字符串来实现。

以下是使用ansi命令和插值的示例,使用$""进行插值:

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

现在,要查看"under the hood"发生了什么,您可以运行以下命令:

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

这将产生类似于以下结果:

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

现在更容易看出是通过ansi转义来实现的。这意味着我们可以像这样使用相同的结果:

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

关键在于,在nushell中,双引号表示要翻译转义字符。如果您使用单引号或反引号,您将得到一个字符串,而不是红色字符串。

英文:

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.

huangapple
  • 本文由 发表于 2023年4月11日 04:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定