How to get osx shell script to show colors in echo

MacosBashShellEcho

Macos Problem Overview


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:

#!/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.

enter image description here

Macos Solutions


Solution 1 - Macos

Use \033 or \x1B instead of \e to represent de <Esc> character.

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

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

Solution 2 - Macos

OSX ships with an old version of Bash that does not support the \e escape character. Use \x1B or update Bash (brew install bash).

Even better, though, would be to use tput.

Solution 3 - Macos

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

#!/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:

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

Solution 4 - Macos

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

#!/bin/zsh

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnycynikView Question on Stackoverflow
Solution 1 - MacosguapoloView Answer on Stackoverflow
Solution 2 - MacosdanemacmillanView Answer on Stackoverflow
Solution 3 - Macoscu39View Answer on Stackoverflow
Solution 4 - MacosAdam MatanView Answer on Stackoverflow