Skip to content

Instantly share code, notes, and snippets.

@walkerdb
Last active March 29, 2021 06:17
Show Gist options
  • Save walkerdb/1ce78b52fad72be515efdcabef670c1a to your computer and use it in GitHub Desktop.
Save walkerdb/1ce78b52fad72be515efdcabef670c1a to your computer and use it in GitHub Desktop.
# Terminal text formatting functions, using ANSI escape sequences with specific formatting codes.
# Most terminals recognize these as special character sequences that say basically
# "anything after this sequence should be bold" (code 1) or "blue" (94) or "italic" (3), etc.
#
# The main `text_formatting_escape_sequence` function here just wraps any given args in the sequence
# for the given formatting code, closing it with the "reset all styles" code (0).
#
# Further reading: https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797
function text_formatting_escape_sequence { echo -e "\033[${1}m${*:2}\033[0m"; }
function bold { text_formatting_escape_sequence 1 "$@"; }
function italic { text_formatting_escape_sequence 3 "$@"; }
function underline { text_formatting_escape_sequence 4 "$@"; }
function strikethrough { text_formatting_escape_sequence 9 "$@"; }
function print_blue { text_formatting_escape_sequence 94 "$@"; }
function print_red { text_formatting_escape_sequence 91 "$@"; }
function print_yellow { text_formatting_escape_sequence 93 "$@"; }
# this logic is based on the "using out-of-phase sine waves to make rainbows" section described
# here https://krazydad.com/tutorials/makecolors.php, implemented in bash.
# Uses the more modern rgb escape code sequence (ESC[38;2;{red};{green};{blue}m)
# It's uh, very slow
function print_rainbow {
local text_to_print=$1
local result=""
local frequency
frequency=$(echo "3.14159 * 1.8 / ${#text_to_print}" | bc -l)
for (( i=0; i<${#text_to_print}; i++ )); do
red=$(echo "s(${frequency}*$i + 0) * 127 + 128" | bc -l | cut -d "." -f 1)
green=$(echo "s(${frequency}*$i + 2) * 127 + 128" | bc -l | cut -d "." -f 1)
blue=$(echo "s(${frequency}*$i + 4) * 127 + 128" | bc -l | cut -d "." -f 1)
result="$result\033[38;2;${red};${green};${blue}m${text_to_print:$i:1}\033[0m"
done
echo -e "$result"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment