shaveax
shaveax

Reputation: 478

how to compare IP value in bash?

I have the next command in order to get my current ip address :

ip=$(ifconfig | awk '/inet addr/{print substr($2,6)}' | grep -v "127")

and i want to check if the ip starts with 19 or with 10, with if statement

if [[ $ip =~ "^19*" ]]; then some instructions; fi

but it does not works, i hope you help in this

Upvotes: 0

Views: 1389

Answers (2)

bsrawat
bsrawat

Reputation: 101

Remove double quotes around "^19*"

and loop over $ip as it may have list of ips

Upvotes: 0

Benjamin W.
Benjamin W.

Reputation: 52132

Firstly, your regex would check for 1, 19, 199, 1999 etc., not for "19 or 10". The regex for "starts with 19 or 10" would be ^1[90].

Secondly, if you quote the regex, it is matched as a string, i.e., literally. You could use

if [[ $ip =~ ^1[90] ]]; then

It is good practice to store the regex in a separate variable and then use that variable, unquoted, to avoid all quoting issues:

re='^1[90]'
if [[ $ip =~ $re ]]; then

References:

Upvotes: 3

Related Questions