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

前端 未结 18 1823
生来不讨喜
生来不讨喜 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:12

    ifconfig | grep -oP "(?<=inet addr:).*?(?=  Bcast)"
    

    When using grep to extract a portion of a line (as some other answers do), perl look-ahead and look-behind assertions are your friends.

    The quick explanation is that the first (?<=inet addr:) and last (?= Bcast) parenthesis contain patterns that must be matched, but the characters that match those patters won't be returned by grep, only the characters that are between the two patterns and match the pattern .*? that is found between the sets of parenthesis, are returned.

    Sample ifconfig output:

    eth0      Link encap:Ethernet  HWaddr d0:67:e5:3f:b7:d3  
              inet addr:10.0.0.114  Bcast:10.0.0.255  Mask:255.255.255.0
              UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
              RX packets:1392392 errors:0 dropped:0 overruns:0 frame:0
              TX packets:1197193 errors:0 dropped:0 overruns:0 carrier:0
              collisions:0 txqueuelen:1000 
              RX bytes:1294730881 (1.2 GB)  TX bytes:167208753 (167.2 MB)
              Interrupt:18
    

    This will extract your IP address from the ifconfig output:

    ifconfig | grep -oP "(?<=inet addr:).*?(?=Bcast)"
    

    To assign that to a variable, use this:

    ip=$(ifconfig | grep -oP "(?<=inet addr:).*?(?=Bcast)")
    

    A slightly more in depth explanation:

    From man grep:

    -o Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line.

    -P Interpret the pattern as a Perl regular expression. This is highly experimental and ‘grep -P’ may warn of unimplemented features.

    From permonks.org:

    (?<=pattern) is a positive look-behind assertion

    (?=pattern) is a positive look-ahead assertion

    -o Tells grep to only return the portion of the line that matches the pattern. The look-behinds/aheads are not considered by grep to be part of the pattern that is returned. The ? after .* is important since we want it to look for the very next look-ahead after the .* pattern is matched, and not look for the last look-ahead match. (This is not needed if we added a regex for the IP address instead of .*, but, readability).

提交回复
热议问题