In this article we will provide you code examples to convert hex color to RGB and RGB to hex using bash script. The code will work for both with or without # characters in hex colors.
Code Example –
1. Hex color to RGB –
#!/bin/bash
hex_to_rgb() {
: "${1/\#}"
((r=16#${_:0:2},g=16#${_:2:2},b=16#${_:4:2}))
printf '%s\n' "$r $g $b"
}
hex_to_rgb "#FFFFFF"
# Output:
# 255 255 255
2. RGB to Hex code
#!/bin/bash
rgb_to_hex() {
printf '#%02x%02x%02x\n' "$1" "$2" "$3"
}
rgb_to_hex "255" "255" "255"
# Output:
# #ffffff