0

This is inside of a .sh script file:

cd /somefolder  
IP=$(ifconfig | grep 'inet addr:'| grep 168 | grep 192|cut -d: -f2 | awk '{print $1}')

The /somefolder has another folder list with a single text file in it.

Can someone explain what the above command is doing, it is combining bash, with grep and awk.

Also, To debug this and better understand it, is it possible for me to run this in the command line also?

4

ifconfig leaves you with a block of text like this:

eth0      Link encap:Ethernet  HWaddr aa:aa:aa:aa:aa:aa  
          inet addr:192.168.0.4  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::6ef0:49ff:fe54:b80/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:118583044 errors:0 dropped:0 overruns:0 frame:0
          TX packets:117593447 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:86729976752 (86.7 GB)  TX bytes:96008613785 (96.0 GB)

The first grep filters for lines that contain inet addr:, leaving you with:

          inet addr:192.168.0.4  Bcast:192.168.0.255  Mask:255.255.255.0

The next two grep commands filter again, looking for 192 and 168. I think it's searching for local IPs. Ones that tend to look like 192.168.*.*. Not all local IPs look like that but I'll ignore that for now.

In our example's case, nothing else gets filtered out.

The cut then uses : as a delimiter (cutting point) and takes the second value:

192.168.0.4  Bcast

awk delimits by space by default and it prints the first column, leaving us with:

192.168.0.4

It's a script that tries to get your local IP. It's not very good.If you LAN uses a different addressing format or you have a legal (external) IP with 192 or 168 in it or its mask —like 4.4.168.192— this would incorrectly catch it.

There are probably better ways to get your internal IP than filtering ifconfig output but here's another filtering method that only uses one awk to clean up:

ifconfig | awk -F' |:' '/inet addr:192\.168\./ {print $13}'

It will only work for 192.168.. addresses but that's already better than the existing command.

| improve this answer | |
  • Sorry! It is ifconfig I copied it wrong. – Blankman Jun 16 '14 at 19:25
  • Did you also mean inet addr: instead of my addr:? – Oli Jun 16 '14 at 19:26
  • Oli, yes, I was avoiding copying it exactly b/c I wasn't sure it should be made public, but looks like it is standard tokens. I apologies for leading you the wrong way but I was doing this for a reason. – Blankman Jun 16 '14 at 19:28
  • Yeah that's fair enough. Not an awful idea if you don't know what it means. – Oli Jun 16 '14 at 19:29
  • I've edited to show a step-by-step of what it does. – Oli Jun 16 '14 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.