Features:
- messages formatted with clear borders
- errors sent to stderr
- colour handling
- colours can be included in other strings
echo
ed to the screen without having to use the-e
option - the desired colour can be either a string or a function
- colours can be issued as commands before
echo
ing text
Limitations:
- If the message is longer than the width of the terminal, the output will be strange
- If the message contains newlines, the output will be strange
- Non-colour formatting functions can be passed in
- Non-colour strings can be passed in
- The terminal is assumed to always use the default colours and resets back after each message
Questions:
- Is there a simpler way to get a string of spaces the same length as the message passed in?
- Is there a simpler way to get the output of a function if it exists, or a default value if it doesn't exist?
- My preferred order of function execution is top-to-bottom, but BASH seems to do a single pass, so I've got bottom-to-top because my code immediately calls the functions above it. Is there a standard order of function declarations/definitions in BASH?
I'm very experienced in other languages, but I'm pretty new to BASH, so I could be making newbie mistakes. All feedback gratefully received! (unless it's mean!)
#!/bin/bash
fg_black="\e[30m"
fg_white="\e[37m"
bg_red="\e[41m"
bg_blue="\e[44m"
bg_purple="\e[45m"
black_on_red() { echo -en "$fg_black$bg_red"; }
white_on_blue() { echo -en "$fg_white$bg_blue"; }
black_on_purple() { echo -en "$fg_black$bg_purple"; }
reset_colours() { echo -en "\e[0m"; }
function_or_value() {
func=$(declare -F "$1" 2>/dev/null)
local value=$($func)
echo -n "${value:-$1}"
}
colour_message() {
local colour="$(function_or_value "$1")"
local message=$2
echo "$colour ${message//[^ ]/ } $(reset_colours)"
echo "$colour ${message} $(reset_colours)"
echo "$colour ${message//[^ ]/ } $(reset_colours)"
}
colour_error_message() {
local colour=$1
local message=$2
colour_message >&2 "$colour" "$message"
}
colour_error_message "$(black_on_red)" "Error!!!"
colour_message white_on_blue "No Error!!!"