your daily cup of tea™

powered by

quick and friendly bash terminal colors

Just published vtfmt, a small bash utility to quickly colorize strings without either dragging in a huge library with too much features or having to manually put (and remember) ANSI escape codes. I have tried to keep it as minimal as possible and I am still surprised how far can just three lines go!

The implementation is pretty straightforward. An associative array with friendly names for the different ANSI color codes and a function that appends these as a mode between \033[ and m :)

#!/usr/bin/env bash

declare -A FMT_SET=(
  # Set
  # fg colors
  # bg colors

function vtfmt {
  local out=(); for comp in "$@"; do out+=("${FMT_SET[$comp]}"); done
  IFS=';' ; echo "\033[${out[*]}m"

# script is not sourced
if [[ ${#BASH_SOURCE[@]} -lt 2 ]]; then
  # has arguments
  if [[ $# -gt 0 ]]; then
    vtfmt "$@"
    echo -en "$(vtfmt bg:light-magenta fg:black bold) vtfmt $(vtfmt reset) "
    echo -e "This utility is by no means $(vtfmt fg:green)feature $(vtfmt underline)complete.$(vtfmt reset) "
    echo -e "And yet it can do quite some things considering how $(vtfmt bold)small$(vtfmt normal) it is!"
    echo ""
    declare -f vtfmt
    echo ""

    # or basically anywhere to compose different color modes
    WARN_C="$(vtfmt bg:yellow fg:black) WARN $(vtfmt reverse) %s$(vtfmt reset)\n"
    INF_C="$(vtfmt bg:green fg:black) INFO $(vtfmt reverse) %s$(vtfmt reset)\n"
    ERR_C="$(vtfmt bg:red fg:black)  ERR $(vtfmt reverse) %s$(vtfmt reset)\n"

    function inf  { printf "$INF_C" "$*" ; }
    function err  { printf "$ERR_C" "$*" ; }
    function warn { printf "$WARN_C" "$*" ; }

    inf "some info"
    warn "you have been warned"
    err "such an error"

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


This site uses Akismet to reduce spam. Learn how your comment data is processed.