bash 如何让 osx shell 脚本在 echo 中显示颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28782394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:53:16  来源:igfitidea点击:

How to get osx shell script to show colors in echo

macosbashshellecho

提问by nycynik

I'm trying to add color output to my errors in a bash script that I have running on a mac. The problem is the colors are not working. I created the simplest of scripts to demonstrate that it does not work:

我正在尝试将颜色输出添加到我在 Mac 上运行的 bash 脚本中的错误中。问题是颜色不起作用。我创建了最简单的脚本来证明它不起作用:

#!/bin/bash

echo -e "\e[1;31m This is red text \e[0m"

However, when i run it, I see no colors at all, as shown in this image. The color output of the ls command is working fine however.

但是,当我运行它时,我根本看不到颜色,如图所示。但是 ls 命令的颜色输出工作正常。

enter image description here

在此处输入图片说明

采纳答案by danemacmillan

OSX ships with an old version of Bash that does not support the \eescape character. Use \x1Bor update Bash (brew install bash).

OSX 附带不支持\e转义字符的旧版 Bash 。使用\x1B或更新 Bash ( brew install bash)。

Even better, though, would be to use tput.

不过,更好的是使用tput.

回答by guapolo

Use \033or \x1Binstead of \eto represent de <Esc>character.

使用\033\x1B代替\e来表示<Esc>字符。

echo -e "3[1;31m This is red text 3[0m"

See http://misc.flogisoft.com/bash/tip_colors_and_formatting

http://misc.flogisoft.com/bash/tip_colors_and_formatting

回答by cu39

In script files printfcould be yet another option, you have to add trailing "\n"though.

在脚本文件中printf可能是另一种选择,但您必须添加尾随"\n"

#!/bin/bash

echo -e "\e[31mOutput as is.\e[m"
printf "\e[32mThis is green line.\e[m\n"
printf "\e[33;1m%s\n" 'This is yellow bold line.'

Tested on macOS High Sierra 10.13.6:

在 macOS High Sierra 10.13.6 上测试:

% /bin/bash --version
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17)
Copyright (C) 2007 Free Software Foundation, Inc.

回答by Adam Matan

Another option could be using zsh, which respects the \enotation.

另一种选择是使用 zsh,它尊重\e符号。

#!/bin/zsh