Putting IP Address into bash variable. Is there a better way

前端 未结 18 1870
生来不讨喜
生来不讨喜 2020-12-07 20:09

I\'m trying to find a short and robust way to put my IP address into a bash variable and was curious if there was an easier way to do this. This is how I am currently doing

18条回答
  •  难免孤独
    2020-12-07 21:09

    The following works on Mac OS (where there is no ip commnand or hostname options):

    #!/bin/bash
    
    #get interface used for defalt route (usually en0)
    IF=$(route get default |grep 'interface' |awk -F: '{print $2}');
    
    #get the IP address for inteface IF
    #does ifconfig, greps for interface plus 5 lines, greps for line with 'inet '
    IP=$(ifconfig |grep -A5 $IF | grep 'inet ' | cut -d: -f2 |awk '{print $2}');
    #get the gateway for the default route
    GW=$(route get default | awk '/gateway:/ {print $2}');
    

提交回复
热议问题