-1

This question already has an answer here:

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+.

marked as duplicate by Wildcard, Kiwy, roaima, Jeff Schaller, Archemar Mar 2 '18 at 13:14

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Try using printf instead of echo. See Why is printf better than echo? – Wildcard Mar 2 '18 at 4:00
  • ahhh I think echo -e with the -e flag might do it – Alexander Mills Mar 2 '18 at 4:01
  • I need to support bash versions < 4, looks like printf is 4.1.x – Alexander Mills Mar 2 '18 at 4:03
  • @AlexanderMills printf is certainly in bash 3.2. – Olorin Mar 2 '18 at 4:06
  • 1
    printf is specified by POSIX. That's the point. It essentially doesn't matter what version you use. – Wildcard Mar 2 '18 at 4:07
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.

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}..."
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.