How to test a valid IP address in Linux Bash Shell ?

Here is a quick tip to test a valid IP address on linux bash shell.

I have recently used it in one of the scripts i need to prepare.

I. Test Valid IP address

bash-4.2# echo "192.101.123.12" | awk '/^([0-9]{1,3}[.]){3}([0-9]{1,3})$/{print $1}'
192.101.123.12

 

II. What above awk command does ?
The script returns IP address if it matches:
a. ^([0-9]{1,3}[.]){3} –> Starting text has 3 sets of of any numbers of length 1-3 from “0-9 & .” i.e. 1.1.1.
b. ([0-9]{1,3})$ –> Matches number and end of input IP address i.e. say “1.”
c. When they combined it matched 4 set of numbers seperated by a dot.

III. How to use in shell script ?
In shell script, you can take this output in a variables and check if the variable is “not zero”.

A=`echo "192.101.123.12" | awk '/^([0-9]{1,3}[.]){3}([0-9]{1,3})$/{print $1}'`
if [ -z $A ]; then
   ## IP is not correct and A is null/zero.
else
  ## IP address is correct, and returned
fi

 

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
oblus
oblus
4 years ago

this regex is wrong…. try echos 110.0.0.257