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 "" | awk '/^([0-9]{1,3}[.]){3}([0-9]{1,3})$/{print $1}'


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 "" | 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.
  ## IP address is correct, and returned


0 0 votes
Article Rating
Notify of
1 Comment
Oldest Most Voted
Inline Feedbacks
View all comments
2 years ago

this regex is wrong…. try echos