Issue
I am very new to bash script so basically i can not understand it very much so please can any one suggest me ways that i can learn faster.
I am tryong to write a bash script to read ip adress and validate it. So please can you tell me what mistaking I am making in the script that i have used.
function valid_ip()
{
local IPA1=$1
local stat=1
if [[ $IPA1 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]];
then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
This code also i have taken from the internet itself just to understand the concept but still i cannot get it.
Solution
Please read comments:
function valid_ip()
{
local IPA1=$1
local stat=1
if [[ $IPA1 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]];
then
OIFS=$IFS
IFS='.' #read man, you will understand, this is internal field separator; which is set as '.'
ip=($ip) # IP value is saved as array
IFS=$OIFS #setting IFS back to its original value;
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] # It's testing if any part of IP is more than 255
stat=$? #If any part of IP as tested above is more than 255 stat will have a non zero value
fi
return $stat # as expected returning
You can check the default value of IFS by printf '%q' $IFS
before setting it to any other value.
Answered By - PradyJord Answer Checked By - Robin (WPSolving Admin)