Skip to content

Instantly share code, notes, and snippets.

@mhulse
Last active March 13, 2024 22:15
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mhulse/b11e568260fb8c3aa2a8 to your computer and use it in GitHub Desktop.
Save mhulse/b11e568260fb8c3aa2a8 to your computer and use it in GitHub Desktop.
Bash function to convert hex to 256 terminal color.
# fromhex A52A2A
# fromhex "#A52A2A"
# BLUE_VIOLET=$(fromhex "#8A2BE2")
# http://unix.stackexchange.com/a/269085/67282
function fromhex() {
hex=$1
if [[ $hex == "#"* ]]; then
hex=$(echo $1 | awk '{print substr($0,2)}')
fi
r=$(printf '0x%0.2s' "$hex")
g=$(printf '0x%0.2s' ${hex#??})
b=$(printf '0x%0.2s' ${hex#????})
echo -e `printf "%03d" "$(((r<75?0:(r-35)/40)*6*6+(g<75?0:(g-35)/40)*6+(b<75?0:(b-35)/40)+16))"`
}
@mhulse
Copy link
Author

mhulse commented Mar 12, 2016

@mhulse
Copy link
Author

mhulse commented Mar 12, 2016

Testing:

ALICE_BLUE=$(fromhex "#A52A2A")
echo $ALICE_BLUE
echo $(tput setaf $ALICE_BLUE)djdjdj$(tput sgr0)

@laedanrex
Copy link

nice

@stefanofiorentino
Copy link

Thanks to this I've created a C/C++ version

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