nycynik
nycynik

Reputation: 7541

How to get osx shell script to show colors in echo

I'm trying to add color output to my errors in bash on a Mac. The colors are not working:

#!/bin/bash

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

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

Upvotes: 73

Views: 49560

Answers (6)

guapolo
guapolo

Reputation: 2543

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

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

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

Upvotes: 121

Victor
Victor

Reputation: 31

A quick exemple of how you can change text color. It's working with many different version of bash (Mac OS ready also tested on fedora 33 KDE and ubuntu jellyfish gnome).

In this exemple to show you how it work I use echo command with -e option to enable interpret backslash escapes and then use the this part \x1B[HX;Ym to start text modification.

H for  Highlight option
H = 3 --> Color text       H = 4 --> Highlight text

X for the color
X = 1 --> Red              X = 2 --> Green
X = 3 --> Yellow/orange    X = 4 --> Blue light
X = 5 --> Purple           X = 6 --> Blue dark

Y for the format
Y = 1 --> Bold             Y = 2 --> Normal
Y = 3 --> Italic           Y = 4 --> Underline

When you finish text modification use \x1B[0m

Try on your terminal :

echo -e "Hello my name is \x1B[34;2mVictor\x1B[0m I'm a \x1B[33;2msys-admin\x1B[0m \!\n"

https://github.com/victor-sys-admin/MODIFY_TEXT_OUTPUT_COLOR_BASH

Upvotes: 3

MBH
MBH

Reputation: 16609

I wrote functions from @cu39 answer and used it like this:

#!/bin/bash

printy() {
  printf "\e[33;1m%s\n" "$1"
}
printg() {
  printf "\e[32m$1\e[m\n"
}
printr() {
  echo -e "\033[1;31m$1\033[0m"
}

printr "This is red"
printy "This is yellow"
printg "This is green"

The result:

enter image description here

Upvotes: 5

cu39
cu39

Reputation: 171

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.

Upvotes: 17

Adam Matan
Adam Matan

Reputation: 136141

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

#!/bin/zsh

Upvotes: 6

danemacmillan
danemacmillan

Reputation: 1242

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.

Upvotes: 58

Related Questions