Parse ifconfig to get only my IP address using Bash

后端 未结 20 1228
甜味超标
甜味超标 2020-11-30 05:04

I want to edit the bashrc file to have a simple function called \"myip\" to run. As you might guess, the function myip prints only my internal IP address of my machine.

20条回答
  •  天命终不由人
    2020-11-30 05:41

    This code outputs IP addresses for all network connections (except loopback) and is portable between most OS X and Linux versions.

    It's particularly useful for scripts that run on machines where:

    • The active network adapter is unknown,
    • notebooks that switch between Wi-Fi and Ethernet connections, and
    • machines with multiple network connections.

    The script is:

    /sbin/ifconfig -a | awk '/(cast)/ {print $2}' | cut -d: -f2
    

    This can be assigned to a variable in a script like this:

    myip=$(/sbin/ifconfig -a | awk '/(cast)/ {print $2}' | cut -d: -f2)
    

    Scripts can handle possible multiple addresses by using a loop to process the results, as so:

    if [[ -n $myip ]]; then
      count=0
      for i in $myip; do
        myips[count]=$i       # Or process as desired
        ((++count))
      done
      numIPaddresses=$count   # Optional parameter, if wanted
    fi
    

    Notes:

    • It filters 'ifconfig' on "cast", as this has an added effect of filtering out loopback addresses while also working on most OS X and Linux versions.
    • The final 'cut' function is necessary for proper function on Linux, but not OS X. However, it doesn't effect the OS X results - so it's left in for portability.

提交回复
热议问题