![]() It does require an ip command that produces JSON output (some say the BusyBox ip command cannot do this), the CLI jq parser that can extract fields from JSON input, and your machine has to know how to get to the public IP at 8.8.8.8. If by " my ip address" you mean " the IP address my machine will use to get to the public Internet to which I am connected", then this very tidy JSON answer may work for you, depending on what O/S your machine runs: ip=$( ip -j route get 8.8.8.8 | jq -r '.prefsrc' ) (This is not needed if we added a regex for the IP address instead of. * pattern is matched, and not look for the last look-ahead match. * is important since we want it to look for the very next look-ahead after the. The look-behinds/aheads are not considered by grep to be part of the pattern that is returned. o Tells grep to only return the portion of the line that matches the pattern. (?=pattern) is a positive look-ahead assertion (?<=pattern) is a positive look-behind assertion This is highly experimental and ‘grep -P’ may warn of unimplemented features. P Interpret the pattern as a Perl regular expression. o Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line. To assign that to a variable, use this: ip=$(ifconfig | grep -oP "(?<=inet addr:).*?(?=Bcast)") ![]() This will extract your IP address from the ifconfig output: ifconfig | grep -oP "(?<=inet addr:).*?(?=Bcast)" TX packets:1197193 errors:0 dropped:0 overruns:0 carrier:0 ![]() RX packets:1392392 errors:0 dropped:0 overruns:0 frame:0 ![]() UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 Sample ifconfig output: eth0 Link encap:Ethernet HWaddr d0:67:e5:3f:b7:d3 *? that is found between the sets of parenthesis, are returned. 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. 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. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |