Script to convert hex color codes to RGB and RGB to HEX on the fly!

#1

col.sh


usage() {
    echo ""
    echo "$0 - Convert hex color code to RGB and RGB to HEX (Hexadecimal)"
    echo ""
    echo "Usage: $0 [HEX] or [RGB] color value"
    echo ""
    echo "Example HEX to RGB: $0 0000ff"
    echo "Example RGB to HEX: $0 0,0,255"
    echo ""
    exit 1
}

if [ $# -eq 0 ]; then
    echo 'Invalid color value!';
    usage;
fi

if [[ $1 =~ ([[:xdigit:]]{2})([[:xdigit:]]{2})([[:xdigit:]]{2}) ]]; then
    printf "(%d, %d, %d)\n" \
           0x"${BASH_REMATCH[1]}" 0x"${BASH_REMATCH[2]}" 0x"${BASH_REMATCH[3]}"
elif [[ $1 =~ ([[:digit:]]{1,3}),([[:digit:]]{1,3}),([[:digit:]]{1,3}) ]]; then
    printf "#%02x%02x%02x\n" \
           "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}"
fi

Example: type in terminal: col.sh 0000ff [enter]
Result: [ ( 0, 0, 255) ]

                      OR

col.sh 0,0,255 [enter]
#0000ff

and it is from here: https://github.com/ivoarch/bin/blob/master/colors/col.sh

6 Likes

#2

Hell yeah. Thanks, that’s helpful!

1 Like

#3

Thanks @subjunkie !

2 Likes

#4

@Negata @Dobbie03 Thank you.

2 Likes

#5

Cool! Very helpful.

1 Like

#6

Thx @subjunkie .

1 Like

#7

I’ve already tried it with my favorite green

col

2 Likes

#8

@subjunkie hallelujah - at last!

I cant count the number of times I have needed this. If you are in town, I’ll buy you many beers.

3 Likes

#9

@philT Hahhaha! Now that is what i calling a deal! :wink:

1 Like