shellhexdecimalrgb

Convert hexadecimal color to decimal RGB values in UNIX shell script


I'm sure someone has already solved this problem: what is an easy and portable way to convert a hex color value (anything from 000000 to FFFFFF) to 3 decimal values from 0 to 255. (If you're not familiar with how colors are traditionally represented in HTML, the first two hex digits are the first decimal number, and so forth.)


Solution

  • If you need a POSIX compatible version of this script that handles more valid CSS hex color formats (ie: 4-part with alpha channel #AABBCCDD, 3 char shortcuts #FFF), this should do the trick:

    #!/bin/sh
    ##? ~/bin/hex2rgb - convert color hex to rgb
    # '#C0FFEE' => 192 255 238
    # 'DEADBEEF' => 222 173 190 239
    # 'fab' => 255 170 187
    __hex2rgb() {
      # reset $1 to scrubbed hex: '#01efa9' becomes '01EFA9'
      set -- "$(echo "$1" | tr -d '#' | tr '[:lower:]' '[:upper:]')"
      START=0
      STR=
      while (( START < ${#1} )); do
        # double each char under len 6 : FAB => FFAABB
        if (( ${#1} < 6 )); then
          STR="$(printf "${1:${START}:1}%.0s" 1 2)"
          (( START += 1 ))
        else
          STR="${1:${START}:2}"
          (( START += 2 ))
        fi
        echo "ibase=16; ${STR}" | bc
      done
      unset START STR
    }
    __hex2rgb "$@"