Bash_Scripts/Templates/Functions/RGB-Terminal-Colors.bash
2022-01-17 10:25:33 -06:00

116 lines
3.2 KiB
Bash
Executable File

#!/bin/bash
rgb() {
# Echo a color printf to the terminal awaiting an actual echo to be colored
# should be used with reset after coloring a string
#
# Positional Arguments:
# red <type: int> <position: 1> <required: true>
# - The red value from 0 to 255
# green <type: int> <position: 2> <required: true>
# - The green value from 0 to 255
# blue <type: int> <position: 2> <required: true>
# - The blue value from 0 to 255
#
# Usage:
# echo_rgb 10 80 3 && echo "hello" && reset
#
# POSIX Compliant:
# N/A
#
red="${1}"
green="${2}"
blue="${3}"
printf "\e[0;38;2;%s;%s;%sm" "${red}" "${green}" "${blue}"
}
echo_rgb() {
# Echo a colored string to the terminal based on rgb values
#
# NOTE: This function will only truly work with terminals that support TRUE COLOR, see:
# https://gist.github.com/XVilka/8346728
#
# Positional Arguments:
#
# message <type: string> <position: 1> <required: true>
# - The message to be printed to stdout
# red <type: int> <position: 2> <required: true>
# - The red value from 0 to 255
# green <type: int> <position: 3> <required: true>
# - The green value from 0 to 255
# blue <type: int> <position: 4> <required: true>
# - The blue value from 0 to 255
# bg_red <type: int> <position: 5> <required: false>
# - The background red value from 0 to 255
# bg_green <type: int> <position: 6> <required: false>
# - The background green value from 0 to 255
# bg_blue <type: int> <position: 7> <required: false>
# - The background blue value from 0 to 255
#
# Usage:
# echo_rgb "Yep" 10 80 30
# echo_rgb "DESTROY MY EYES" 255 0 255 0 255 0
#
# POSIX Compliant:
# N/A
#
local red
local green
local blue
local input
local bg_red
local bg_green
local bg_blue
input="${1}"
red="${2}"
green="${3}"
blue="${4}"
bg_red="${5}"
bg_green="${6}"
bg_blue="${7}"
for num in "${@:2}"; do
[[ ! "${num}" =~ [0-9] ]] &&
echo "Given RGB value was not a number, received ${num}" &&
return 1
[[ "${num}" -gt 255 ]] &&
echo "Given RGB value must be less than 255, received ${num}" &&
return 1
[[ "${num}" -lt 0 ]] &&
echo "Given RGB value must be more than 0, received ${num}" &&
return 1
done
if [ -t 1 ]; then
if [ -n "${5}" ]; then
[[ -z "${6}" ]] && echo "A value must be passed for bg_green" && return 1
[[ -z "${7}" ]] && echo "A value must be passed for bg_blue" && return 1
printf "\033[38;2;%s;%s;%s;48;2;%s;%s;%sm%s\033[m\n" \
"${red}" "${green}" "${blue}" "${bg_red}" "${bg_green}" "${bg_blue}" "${input}"
else
printf "\033[0;38;2;%s;%s;%sm%s\033[m\n" "${red}" "${green}" "${blue}" "${input}"
fi
else
printf "%s\n" "${input}"
fi
return 0
}
reset() {
# Reset colors in the terminal to default
#
# Usage:
# reset
#
# POSIX Compliant:
# N/A
#
printf "\e[m\n"
}