ansi escape codes interface/non-hardcoded mapping

50 views Asked by At

bash has support for ansi escape codes. i would like to use fancy and pretty printing of some test in a script. since i didn't find any basic builtin\lib\tool\script that provide this functionality, it seems that i have to use a hardcoded mapping between names and escape codes, e.g.

RESET="0"
BOLD="1"
FAINT="2"
ITALIC="3"
# etc.
FG_RED="31"
BG_RED="41"

is there any builtin\lib\tool\script that gives a simple interface/tool/lib/etc. to use ansi colors and effect in bash? if not, how can i retrieve the mapping somehow?

1

There are 1 answers

4
TheAnalogyGuy On

I usually drop something like this in at the top of my scripts..

# print color (no previous dependency on setting colors)
#---------------------------------
# color formatting and stuff
#---------------------------------
# print a string in color, with no \n
# e.g. printcn red "some text"
printcn() {
  local m="${*:-$(read -t 0.01 m; echo "${m}")}"
  #local m="${@}"
  local c="${m%% *}"  # color would be in first word
  # see if first word (lowercase) matches a color
  case "${c,,}" in
    -n|nc|norm|normal) m="$(tput sgr0   )${m#* }" ;;
    -r|red)            m="$(tput setaf 1)${m#* }" ;;
    -g|grn|green)      m="$(tput setaf 2)${m#* }" ;;
    -y|yel|yellow)     m="$(tput setaf 3)${m#* }" ;;
    -b|blu|blue)       m="$(tput setaf 4)${m#* }" ;;
    -m|mag|magenta)    m="$(tput setaf 5)${m#* }" ;;
    -c|cya|cyan)       m="$(tput setaf 6)${m#* }" ;;
    -w|whi|white)      m="$(tput setaf 7)${m#* }" ;;
  esac
  printf -- '%s' "${m}$(tput sgr0)"
} >&2

# Print color with newline
printc() {
  local in
  in="${*:-$(read -t 0.01 in; echo "${in}")}"
  printcn "${in}"; printf '\n'
} >&2

Then I can do things like this:

printc -r this is red text
printc blue "This is blue"

enter image description here

Take a look at (https://github.com/kigster/bashmatic) or a script like this: bashmatic