-1

I have this:

ql_gray='\033[1;30m'
ql_magenta='\033[1;35m'
ql_cyan='\033[1;36m'
ql_orange='\033[1;33m'
ql_green='\033[1;32m'
ql_no_color='\033[0m'

I use them like so:

echo "${ql_magenta}quicklock: could not acquire lock with name '${qln}'${ql_no_color}."

but I get this:

\033[1;35mquicklock: could not acquire lock with name '/Users/me/.quicklock/locks/_oresoftware.lock'\033[0m.

is there some flag I need to set in order to get control chars to be recognized?

Is there some flag I can check to see if the end user has allowed control chars to be recognized? If they aren't recognized, then I can just set the above to:

ql_gray=''
ql_magenta=''
ql_cyan=''
ql_orange=''
ql_green=''
ql_no_color=''

I need to support Bash versions 3+.

3 Answers3

3

The portable way to do this is to use tput:

ql_gray=$(tput setaf 7)
ql_magenta=$(tput setaf 5)
ql_cyan=$(tput setaf 6)
ql_orange=$(tput setaf 3)
ql_green=$(tput setaf 2)
ql_no_color=$(tput sgr0)

This will take the current terminal settings into account. The official colour list is documented in the terminfo(5) manpage, but you might need to experiment — for example in the list above, 7 is officially white (but ends up light gray in most terminals), and 3 is officially yellow (but ends up dark yellow or orange in most terminals). You can disable colours by setting TERM=dumb before calling tput.

Stephen Kitt
  • 434,908
2

You need to get bash to interpret the escape sequences in the strings there. You can use either of:

echo -e "${ql_gray}..."
printf "%b\n" "${ql_gray}..."

Or evaluate them when setting the variables:

ql_gray=$'\033[1;30m'

Then either of:

echo "${ql_gray}..."
printf "%s\n" "${ql_gray}..."
Olorin
  • 4,656
1

Instead of using echo, use echo -e, using that flag will recognize control chars.

printf might work too, it's a POSIX thing apparently