In this article we will provide you bash script code to check if string is a hex code of a color. A color hex code starts with # followed by 3 or 6 hexadecimal numbers 0-9A-F.
Code Example –
#!/bin/bash
is_hex_color() {
[[ $1 =~ ^(#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3}))$ ]] && echo "${BASH_REMATCH[1]}"
}
# This color code is wrong. 4 characters
color="#FFFF"
# regex validation will fail so color will get RED value
is_hex_color "$color" || color="RED"
echo $color # output = RED
second_color="#FFF" # Correct color hex
is_hex_color "$second_color" || second_color="RED"
echo $second_color # output = "#FFF"