Saturday, October 29, 2022

[SOLVED] Shell script to validate hex value

Issue

How to validate whether the given input string is valid Hex value or not using regex in shell scripts

For example:

Input var="ff:ff:fe:ff"

There is a : deliminator value

I want to use this regex for any input String

var = "ff:ff:fe:ff:fe"
var = "ff:ff:fe:ff:fe:fe:ff:ff"
\b0[xX][0-9a-fA-F]+\b



#!/bin/bash -x
var="fe:fe:fe:fe"
regex="/^([0-9A-F]+:?){4}$/"
if [[ $var =~ $regex ]]; then
echo "valid"
fi

Solution

Better version (thanks to chepner):

^([[:xdigit:]]{2})(:[[:xdigit:]]{2})*$

Test

if [[ "ff:af:ff:23:a2:ad" =~ ^([[:xdigit:]]{2})(:[[:xdigit:]]{2})*$ ]]; then
   echo "match";
fi

Old Answer:

^([0-9A-Fa-f]{2})(:[0-9A-Fa-f]{2})*$

Test

$ if [[ "ff:af:ff:23:a2:ad" =~ ^([0-9A-Fa-f]{2})(:[0-9A-Fa-f]{2})*$ ]]; then 
   echo "match"; 
  fi 
$ match

$ if [[ "definitlynottherightformat" =~ ^([0-9A-Fa-f]{2})(:[0-9A-Fa-f]{2})*$ ]]; then 
   echo "match"; 
  fi 
$


Answered By - Tom Regner
Answer Checked By - Willingham (WPSolving Volunteer)