Parse ifconfig to get only my IP address using Bash

后端 未结 20 1223
甜味超标
甜味超标 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:43

    A simple AWK + Bash script example which may give general idea how to parse command output and mix syntaxes together.

    Full code is at: https://gist.github.com/darkphase/67d7ec22d47dbebd329e

    BEGIN { RS = "" ; FS = "\n" }  # Change separator characters
    {
        while ( "'"$cmd"'" | getline ){
            # print $0
            if ( $1 !~ /LOOPBACK/ ){
    
                split($1,arr," ")
                print "'"$blue"'"arr[1]"'"$reset"'"
    
                for(i = 1; i <= NF; i++) { # Loop through fields (this case lines)
                    split($i,arr," ")
                    switch ( arr[1] ) {
                        case "inet":
                            print "'"$red"'" "IPV4:" "'"$reset"'" "\n IP: " "'"$yellow"'" arr[2] "'"$reset"'" "\n NM: "arr[4]"\n BC: "arr[6]
                            break
                        case "inet6":
                            print "'"$red"'" "IPV6:" "'"$reset"'" "\n IP: "arr[2]"\n PL: "arr[4]
                            break
                        case "ether":
                            print "'"$red"'" "MAC: " "'"$reset"'" arr[2]
                            break
                        default:
                    }
                }
                print ""
            }
        }
    }'
    

提交回复
热议问题