Braxton Fair
Braxton Fair

Reputation: 13

Match hex color code in bash

I've looked around a little bit and I can't seem to find a working way to verify(in regex) if a given argument is a hex color code. Here is my code that I have:

echo `expr match "$1" '\(#[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})\)'`

When I put it into a file (hex.sh), it returns nothing whereas it should return the code itself. Am I wrong or what should the code be?

Upvotes: 1

Views: 798

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

expr match "$string" '($regexp)'

curly brackets {} and "pipeline" character| as well as regular brackets () should be escaped within $regexp argument.
Use the following adjustment:

#!/bin/bash/
echo `expr match "$1" '\(#[A-Fa-f0-9]\{6\}\|#[A-Fa-f0-9]\{3\}\)'`

Test output:

$ sh hex.sh "#542541"
#542541

Upvotes: 1

Related Questions