0

I am able to validate IPv6 addresses using java with following regex:

([0-9a-fA-F]{0,4}:){1,7}([0-9a-fA-F]){0,4}

But I need to do this in shell script to which I am new.

This regex doesn't seem to work in shell. Have tried some other combinations also but nothing helped.

#!/bin/bash
regex="([0-9a-fA-F]{0,4}:){1,7}([0-9a-fA-F]){0,4}"
var="$1"

if [[ "$var" =~ "$regex" ]]
then
        echo "matches"
else
        echo "doesn't match!"
fi

It gives output doesn't match! for 2001:0Db8:85a3:0000:0000:8a2e:0370:7334

How can I write this in shell script?

11
  • 1
    Same regex should work. Can you show your shell script code? Commented Aug 8, 2017 at 10:12
  • Have added script to question. Commented Aug 8, 2017 at 10:19
  • 1
    Also you should anchor your regex: regex='^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$' Commented Aug 8, 2017 at 10:21
  • 1
    May I suggest that you re-edit and leave the original error? Else the question does not make sense any more and readers with similar questions could get puzzled. Commented Aug 8, 2017 at 10:29
  • 1
    @anubhava please answer it and I will accept the answer. Commented Aug 8, 2017 at 10:30

2 Answers 2

8

Java regex shown in question would work in bash as well but make sure to not to use quoted regex variable. If the variable or string on the right hand side of =~ operator is quoted, then it is treated as a string literal instead of regex.

I also recommend using anchors in regex. Otherwise it will print matches for invalid input as: 2001:0db8:85a3:0000:0000:8a2e:0370:7334:foo:bar:baz.

Following script should work for you:

#!/bin/bash

regex='^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$'
var="$1"

if [[ $var =~ $regex ]]; then
    echo "matches"
else
    echo "doesn't match!"
fi
Sign up to request clarification or add additional context in comments.

3 Comments

1:1:1:1 is valid IP?
In the context of this problem, yes
Brilliant... works on multiple IPv6 patterns. Well done!
3

[[ and =~ won't work with sh, and awk almost works everywhere. Here is what I did

saved as ./check-ipv6.sh, chmod +x ./check-ipv6.sh

#!/bin/sh

regex='^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$'
echo -n "$1" | awk '$0 !~ /'"$regex"'/{print "not an ipv6=>"$0;exit 1}'

Or you prefer bash than sh

#!/bin/bash

regex='^([0-9a-fA-F]{0,4}:){1,7}[0-9a-fA-F]{0,4}$'
awk '$0 !~ /'"$regex"'/{print "not an ipv6=>"$0;exit 1}' <<< "$1"

Test

~$ ./check-ipv6.sh 2001:0Db8:85a3:0000:0000:8a2e:0370:7334x
not an ipv6=>2001:0Db8:85a3:0000:0000:8a2e:0370:7334x
~$ echo $?
1

~$ ./check-ipv6.sh 2001:0Db8:85a3:0000:0000:8a2e:0370:7334
~$ echo $?
0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.