For as long as I can remember, I've personally used the following method for changing the color of output text when using bash:
red=$'\033[1;31m'
nc=$'\033[0m'
echo "${red}This is red text$nc"
It's always worked for me no matter if used on macOS or Linux. Out of curiosity, to better understand why it works, I've done a bit of research and have found some answers/examples that don't include $
(red='\033[1;31m'
). After some testing, if I don't use $
, the output color doesn't change to red, rather it just prints the string. Though, when executing it using sh
instead of bash
, the text does change color. Can someone help me understand why this is?
I've additionally tested it with double quotes instead of single quotes, and it only seems to work when using sh
. I'll post examples below.
This is the script and code I used:
#!/bin/bash
red=$'\033[1;31m'
nc=$'\033[0m'
echo "${red}Test 1$nc"
echo ""
##########################
red=$"\033[1;31m"
nc=$"\033[0m"
echo "${red}Test 2$nc"
echo ""
##########################
red='\033[1;31m'
nc='\033[0m'
echo "${red}Test 3$nc"
echo ""
##########################
red="\033[1;31m"
nc="\033[0m"
echo "${red}Test 4$nc"
echo ""
Output on macOS with both bash and sh:
Output on Linux with both bash and sh:
TERM
isn't one of the ones that accepts those codes (or if your output is going to a non-terminal destination such as a pipe). The portable way isred=$(tput setaf 1)
. That will produce the empty string when used on a dumb terminal, for example. – Toby Speight Jul 12 '22 at 13:30