Skip to content

Instantly share code, notes, and snippets.

@NerdyDeedsLLC
Last active June 12, 2023 19:23
Show Gist options
  • Save NerdyDeedsLLC/183f111b5d18ee5565ec88f47b1ec557 to your computer and use it in GitHub Desktop.
Save NerdyDeedsLLC/183f111b5d18ee5565ec88f47b1ec557 to your computer and use it in GitHub Desktop.
Provides full hex color (#FF0000, #0F0, BADA55, D0A, etc) to Bash terminal
# clr
# Provides full hex color (#FF0000, #0F0, BADA55, D0A), etc) to Bash terminal
#
# clr <HEX COLOR> outputs the control character to set the desired foreground color:
# clr \#FFF (or clr '#FFF') # will set the foreground white.
# clr -b <HEX COLOR> uses the -b flag to output the control character to set the desired background color:
# clr -b #FF0000 # will set the background red
# clr with no parameters resets to default.
#
# The following aliases and shortcuts are also supported:
# - cF <HEX COLOR> will return the control character to set the foreground to <HEX COLOR>
# - cB <HEX COLOR> will return the control character to set the background to <HEX COLOR>
# - cSet <SHORTHAND NAME> (-b) <HEX COLOR> will create a shorthand variable: cSet RED \#F00
# - $X will reset back to normal.
#
# Usage: These return the CHARACTERS that perform these controls. As such, they're intended to be
# either used INSIDE a string, or set to a variable that is used inside a string. For example:
# echo "$(clr \#F00)Hello World!$(clr)"
# -or-
# RED="$(clr \#F00)"
# echo "${RED}Hello World!${X}"
# -or-
# cSet RED \#F00
# echo "${RED}Hello World!${X}"
#
# Installation:
# Just add the following lines to your .bash_profile.
#
# License: Offensive Limerick (bit.ly/limlic)
# Just stick a link to this gist in a comment and go to town.
function clr {
[[ "$1" != "-b" ]] && HEX="$1"
[[ "$1" == "-b" ]] && HEX="$2" && local OPMODE=4
[[ "$HEX" == "" ]] && echo -e "\033[0m" && return 0
HEX="$(sed -E "s/[^a-f0-9]//gi" <<< "$HEX" | sed -E "s/^(.)(.)(.)\$/\1\1\2\2\3\3/gi")"
printf "\033[${OPMODE-3}8;2;%d;%d;%dm" $(echo "ibase=16; ${HEX:0:2}" | bc) $(echo "ibase=16; ${HEX:2:2}" | bc) $(echo "ibase=16; ${HEX:4:2}" | bc)
}
function cSet { eval "$1='$(clr $2 $3)'"; }
cSet X
alias cF="clr $*"
alias cB="clr -b $*"
@NerdyDeedsLLC
Copy link
Author

If you can think of a means to reduce this still further without sacrificing any of the functionality, I welcome your input!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment