Hello! I studied Computer Science, and live in Bath. I write code, design games, and occasionally tweet.
Hello! I studied Computer Science, and live in Bath. I write code, design games, and occasionally tweet.

Colourful Consoles with Bash Aug. 14, 2017 in Bash, Text, Tutorial

With bash it is trivially easy to produce nice, colourful console output with the code below. Simply paste it into the top of your script, and then you can colour your text by just printing the variables.

For example, if you want bold yellow text with a red background use echo "${BOLD}${YELLOW}${BRED}Critical Warning!${CLEAR}". Additionally, you can ${ITALIC}, ${UNDERLINE}, ${INVERT}, or ${STRIKE} text as you see fit. Once you are done with formatted text, use ${CLEAR} to clear all formatting.

Lastly, ${RESET} and ${RULE} to reset the screen and create a horizontal rule. Vertical rules are left as an exercise for the reader.

#!/bin/bash

CLEAR="\033[0m"; BOLD="\033[1m"; ITALIC="\033[3m"; UNDERLINE="\033[4m"; INVERT="\033[7m"; STRIKE="\033[9m
RED="\033[31m"; GREEN="\033[32m"; YELLOW="\033[33m"; BLUE="\033[34m"; PINK="\033[35m"; CYAN="\033[36m"; WHITE="\033[37m"
BRED="\033[41m"; BGREEN="\033[42m"; BYELLOW="\033[43m"; BBLUE="\033[44m"; BPINK="\033[45m"; BCYAN="\033[46m"; BWHITE="\033[47m"

alias RESET='printf "\033c"'
alias RULE='printf %"$COLUMNS"s | tr " " "-"'

# Use $LINES and $COLUMNS to query console dimensions

Get an email when I post, zero spam     Get an email when I post     Newsletter