1

I need to put the IP of my VPS machine into a variable. I mean to the external IP address appearing the value of inet addr section, in ifconfig output.

I've tried:

ipa="$(hostname -i)"

But echo ${ipa} brought the localhost token: 127.0.1.1, so I looked for other solutions and all I found includes many pipes and awk operations which I know nothing about (never used awk and I'm not very familiar with regex).

I tried this:

ipa=$(ifconfig | grep "inet addr:[0-999]\.[0-999]\.[0-999]\.[0-999]")

But it failed given that echo ${ipa} has an empty line of output.

Why did what I've tried failed or at least how would you solve it?

  • It is most important for me to understand what why I tried failed (please review my question edit). –  Dec 12 '17 at 12:25

2 Answers2

2
ipa=$(ifconfig | perl -lane '/inet addr:(\S+)/ and $1 !~ "^127" and print $1')

Also see here for a plethora of alternatives. E.g. using grep:

ipa=$(ifconfig | grep -Po 'inet addr:\K[^\s]+' | grep -v '^127')

Explanation:

ipa=$( ) assign the output of the command in parentheses to the variable ipa
ifconfig show interfaces and their addresses. You might prefer ip address
| grep -Po 'inet addr:\K[^\s]+' filter output using a perl-compatible regex, print the matched text
| grep -v '^127' filter again, this time excluding (-v) values that start (^) with 127


To get my external ip, I usually do:

dig +short myip.opendns.com @resolver1.opendns.com
simlev
  • 1,445
  • 2
  • 12
  • 19
  • So sad I don't know `perl` so at the moment feel uncomfortable to use it (I don't want to use something I don't understand well enough, usually). What do you think on my approach? –  Dec 12 '17 at 11:43
  • @Benia This `perl` code is quite simple, but if you feel uncomfortable then by all means don't use it! Or learn `perl`! Or pick any of the several methods from the linked answers. I added a `grep` alternative, since you already tried with `grep`. – simlev Dec 12 '17 at 11:52
  • I've tried my example only now with `echo` in the end but the output line is empty --- my `grep` failed. –  Dec 12 '17 at 12:01
1
grep "inet addr:[0-999]\.[0-999]\.[0-999]\.[0-999]"

That would match the string inet addr: followed by a single character that is a digit from 0 to 9, or a 9, or a 9, followed by a dot, then another character that is 0 to 9 or 9 or 9... e.g. inet addr:1.2.3.4, but not inet addr:11.22.33.44.

Bracket groups don't match strings that form numbers, just single characters.

ilkkachu
  • 133,243
  • 15
  • 236
  • 397
  • Additionally, even if it worked, it's going to return the entire line, containing `inet addr: .......` not just the IP address. – EightBitTony Dec 12 '17 at 13:31
  • @EightBitTony this is because I didn't wrap the bracket gripus in parenthesis? –  Dec 12 '17 at 13:42