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

nyc*_*nik 36 macos bash shell echo

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

#!/bin/bash

echo -e "\e[1;31m This is red text \e[0m"
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,我看不到任何颜色,如此图所示.然而,ls命令的颜色输出正常工作.

在此输入图像描述

小智 68

使用\033或\x1B代替\e表示de <Esc>character.

echo -e "\033[1;31m This is red text \033[0m"
Run Code Online (Sandbox Code Playgroud)

请参阅http://misc.flogisoft.com/bash/tip_colors_and_formatting

  • 惊人的!非常感谢。不知道为什么它没有标记为正确答案 (2认同)

dan*_*lan 34

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

但是,更好的是使用tput.


Ada*_*tan 5

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

#!/bin/zsh
Run Code Online (Sandbox Code Playgroud)


小智 5

在脚本文件中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.'
Run Code Online (Sandbox Code Playgroud)

在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.
Run Code Online (Sandbox Code Playgroud)