Simple Example – Use Bash Shell to Match IP address


Linux BASH shell is powerful. The shell is a programming environment. You can do the regex match using Shell script. The =~ operator is similar to match() function. And the array is saved at ${BASH_REMATCH[1]}, ${BASH_REMATCH[2]} etc.

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
ip="192.168.0.1"
if [[ $ip =~ ^([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$ ]]
then
    echo "Match"
    echo ${BASH_REMATCH[1]}
    echo ${BASH_REMATCH[2]}
    echo ${BASH_REMATCH[3]}
    echo ${BASH_REMATCH[4]}
else
    echo "Not match"
fi
#!/bin/bash
ip="192.168.0.1"
if [[ $ip =~ ^([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$ ]]
then
    echo "Match"
    echo ${BASH_REMATCH[1]}
    echo ${BASH_REMATCH[2]}
    echo ${BASH_REMATCH[3]}
    echo ${BASH_REMATCH[4]}
else
    echo "Not match"
fi

This will print:

Match
192
168
0
1

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
145 words
Last Post: Linux BASH shell - Echo This if you get angry
Next Post: WordPress Child Theme - The Only Things You Need to Know

The Permanent URL is: Simple Example – Use Bash Shell to Match IP address

2 Comments

  1. Raul Saez

Leave a Reply