Displaying IP address on eth0 interfaceubuntu 1310 with two NICs: one with dynamic address and one with static addressmodem or mobile broadband showing differect ip addressPerform some operation as soon as eth0 is upEth0 lost when ethernet is using crossed cableScript to set IP address connected to an interface to a shell variableip addr show is showing me two IP address on one interfaceAssign IP Address on DNSISC-DHCP server disabled, but “ip address show” still show local IP assigned for eth0How would I ping IP address produced from script?Device eth0 doesnt exist but network is up!

Is it possible to clone a polymorphic object without manually adding overridden clone method into each derived class in C++?

How can a demon take control of a human body during REM sleep?

Create chunks from an array

Sampling from Gaussian mixture models, when are the sampled data independent?

Graphic representation of a triangle using ArrayPlot

Why aren't there more Gauls like Obelix?

What is the purpose of a disclaimer like "this is not legal advice"?

Professor forcing me to attend a conference, I can't afford even with 50% funding

What is this tube in a jet engine's air intake?

PTIJ: Who was the sixth set of priestly clothes for?

Are these two graphs isomorphic? Why/Why not?

How can I portion out frozen cookie dough?

How do you make a gun that shoots melee weapons and/or swords?

How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?

Has a sovereign Communist government ever run, and conceded loss, on a fair election?

Having the player face themselves after the mid-game

Does an unused member variable take up memory?

Is there stress on two letters on the word стоят

If nine coins are tossed, what is the probability that the number of heads is even?

Is this Paypal Github SDK reference really a dangerous site?

Either of .... (Plural/Singular)

Difference between `nmap local-IP-address` and `nmap localhost`

How do I raise a figure (placed with wrapfig) to be flush with the top of a paragraph?

Can the Witch Sight warlock invocation see through the Mirror Image spell?



Displaying IP address on eth0 interface


ubuntu 1310 with two NICs: one with dynamic address and one with static addressmodem or mobile broadband showing differect ip addressPerform some operation as soon as eth0 is upEth0 lost when ethernet is using crossed cableScript to set IP address connected to an interface to a shell variableip addr show is showing me two IP address on one interfaceAssign IP Address on DNSISC-DHCP server disabled, but “ip address show” still show local IP assigned for eth0How would I ping IP address produced from script?Device eth0 doesnt exist but network is up!













18















How can I display the IP address shown on eth0 using a script ?










share|improve this question


























    18















    How can I display the IP address shown on eth0 using a script ?










    share|improve this question
























      18












      18








      18


      11






      How can I display the IP address shown on eth0 using a script ?










      share|improve this question














      How can I display the IP address shown on eth0 using a script ?







      scripts ip






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 11 '14 at 22:56









      user43389user43389

      2782411




      2782411




















          16 Answers
          16






          active

          oldest

          votes


















          25














          save this in a file and then run bash <filename>



          #!/bin/bash
          ifconfig eth0 | grep "inet addr"


          being more accurate to get only number showing IP address:



          #!/bin/bash
          ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1


          Update: If this doesn't works for you, try the other answer






          share|improve this answer




















          • 1





            of course this doesn't work in the latest ubuntu. the latest ifconfig returns "inet <ip>" instead of "inet addr <ip>"

            – thang
            Nov 14 '18 at 23:10


















          21














          For the sake of providing another option, you could use the ip addr command this way to get the IP address:



          ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1



          • ip addr show eth0 shows information about eth0


          • grep "inetb" only shows the line that has the IPv4 address (if you wanted the IPv6 address, change it to "inet6b")


          • awk 'print $2' prints on the second field, which has the ipaddress/mask, example 172.20.20.15/25


          • cut -d/ -f1 only takes the IP address portion.

          In a script:



          #!/bin/bash
          theIPaddress=$(ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1)





          share|improve this answer























          • this solution actually works!

            – thang
            Nov 14 '18 at 23:10


















          16














          Taken from https://stackoverflow.com/a/14910952/1695680



          hostname -i


          However that may return a local ip address (127.0.0.1), so you may have to use, and filter:



          hostname -I


          From hostname's manpages:




          -i, --ip-address



          Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses instead.



          -I, --all-ip-addresses



          Display all network addresses of the host. This option enumerates all configured addresses on all network inter‐faces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this option does not depend on name resolution. Do not make any assumptions about the order of the output.







          share|improve this answer

























          • for the record, I like ip addr show label 'enp*' better, but I is annoying parse, something like ip addr show label 'enp*' | grep -oP inet \S+ | cut -d' ' -f2 can work... how pretty

            – ThorSummoner
            Nov 20 '18 at 23:37


















          4














          @markus-lindberg 's response is my favourite. If you add -o -4 to ip's flags then you get a much more easily parsable (and consistent) output:



          ip -o -4 a | awk '$2 == "eth0" gsub(//.*/, "", $4); print $4 '


          -o stands for --oneline, which is meant to help in exactly this kind of situations. The -4 is added to limit to the IPv4 address, which is what all the other responses imply.






          share|improve this answer























          • Love the ip flags. Using cut rather than advanced awk wizardry: ip -o -4 addr show eth0 scope global | awk 'print $4;' | cut -d/ -f 1

            – DuffJ
            Dec 16 '16 at 14:03











          • @DuffJ it's probably down to a matter of personal taste. I "discovered" cut way after I learned about awk, and I like minimising the number of commands on my pipelines. Nice suggestion in any case.

            – Amos Shapira
            Dec 17 '16 at 6:55











          • I completely agree, Amos. Thanks for your solution!

            – DuffJ
            Dec 19 '16 at 12:34


















          3














          Here are some oneliners.....



          Awk



          ifconfig eth0 | awk '/inet addr/split($2,a,":"); print a[2]'


          split function in the above awk command splits the second column based on the delimiter : and stores the splitted value into an associative array a. So a[2] holds the value of the second part.



          sed



          ifconfig eth0 | sed -n '/inet addr/s/.*inet addr: *([^[:space:]]+).*/1/p'


          In basic sed , (...) called capturing group which is used to capture the characters. We could refer those captured characters through back-referencing. ([^[:space:]]+) captures any character but not space one or more times.



          grep



          ifconfig eth0 | grep -oP 'inet addr:KS+'


          K discards the previously matched characters from printing at the final and S+ matches one or more non-space characters.



          Perl



          ifconfig eth0 | perl -lane 'print $1 if /inet addr:(S+)/'


          One or more non-space characters which are next to the inet addr: string are captured and finally we print those captured characters only.






          share|improve this answer

























          • @edwardtorvalds added some explanation. I think this would be helpful for future readers. Feel free to ask any questions from the above commands... :)

            – Avinash Raj
            Dec 12 '14 at 8:07


















          1














          I suggest using a python library like netifaces that is specifically designed for this purpose.



          sudo pip install netifaces
          python -c "import netifaces; print netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']"


          To obtain the default network interface that is in use.



          default_inf = netifaces.gateways()['default'][netifaces.AF_INET][1]





          share|improve this answer
































            1














            ip addr|awk '/eth0/ && /inet/ gsub(//[0-9][0-9]/,""); print $2'


            This only use ip addr which is a replacement for ifconfig and awk combined with substitution (gsub).



            Stop using too many processes for simple tasks






            share|improve this answer
































              1














              Just one more option that can be useful if you don't have awk (as it is the case in some embedded devices):



              ip addr show dev eth0 scope global | grep "inetb" | cut -d/ -f 1 | egrep -o "([[:digit:]]1,3[.]1)3[[:digit:]]1,3"





              share|improve this answer






























                1














                Here's a good one, only uses grep as secondary command:



                ip addr show eth0 | grep -oP 'inet KS[0-9.]+'



                I don't see why you should use more commands than needed






                share|improve this answer






























                  1














                  ifconfig eth0|grep 'inet '|awk 'print $2'






                  share|improve this answer






























                    1














                    here's for IPv4:



                    ip -f inet a|grep -oP "(?<=inet ).+(?=/)"



                    here's for IPv4 & particular dev (eth0):



                    ip -f inet a show eth0|grep -oP "(?<=inet ).+(?=/)"



                    for IPv6:



                    ip -6 -o a|grep -oP "(?<=inet6 ).+(?=/)"






                    share|improve this answer






























                      1














                      You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                      If you want the IPv4 address for your Ethernet interface eth0:



                      $ ip -4 -o addr show eth0 | awk 'print $4'
                      192.168.1.166/24


                      As a script:



                      $ INTFC=eth0 
                      $ MYIPV4=$(ip -4 -o addr show $INTFC | awk 'print $4')
                      $ echo $MYIPV4
                      192.168.1.166/24



                      The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                      $ ip -4 -o addr show eth0 | awk 'print $4' | cut -d "/" -f 1 
                      192.168.1.166


                      Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                      $ ip route get 8.8.8.8 | awk ' print $NF; exit '
                      192.168.1.166


                      As a script:



                      $ RHOST=8.8.8.8 
                      $ MYIP=$(ip route get $RHOST | awk ' print $NF; exit ')
                      $ echo $MYIP
                      192.168.1.166


                      This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                      While ip would be my preferred approach, it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                      $ hostname --all-ip-addresses | awk 'print $1' 


                      Or, if you want the IPv6 address:



                      $ hostname --all-ip-addresses | awk 'print $2' 


                      As a script:



                      $ MYV4IP=$(hostname --all-ip-addresses | awk 'print $1') 
                      $ MYV6IP=$(hostname --all-ip-addresses | awk 'print $2')
                      $ echo $MYV4IP
                      192.168.1.166
                      $ echo $MYV6IP
                      2601:7c1:103:b27:352e:e151:c7d8:3379





                      share|improve this answer






























                        0














                        this can be used with a normal user too.



                        ip addr show eth0 | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6





                        share|improve this answer

























                        • he ask for eth0, this version of your script could help (also show loopback tho) ip addr show | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6

                          – TiloBunt
                          Mar 25 '17 at 17:01












                        • This is pretty much the same answer as askubuntu.com/a/560466/367990, just using cut twice instead of a combination of awk and cut to parse the output. Next time you should better check out all other answers first and ensure you don't post a duplicate solution. In this case here, I think it's arguable whether it's a duplicate or just similar, so please take it as a general hint. Thanks.

                          – Byte Commander
                          Jul 7 '17 at 19:49


















                        0














                        This is the shortest way I could find:



                        ip -f inet addr show $1 | grep -Po 'inet K[d.]+'



                        Replace $1 with your network interface.



                        ip -f inet tells ip to only return values for the inet (ipv4) family.



                        grep -Po tells grep to interperate the next value as a perl-regex, and only print the matching values.



                        The regex K[d.]+ says "throw away everything up to this point (K), and match as many numeric values followed by a dot in a row as possible". This will therefore only match the IP address and ignore everything after it, including the shortform XX subnet mask.






                        share|improve this answer
































                          0














                          in these days with multiples interfaces (eg if you use a docker) and naming interface by ETH is not anymore the norms



                          I use this command to extract the IP/Mask :



                          IPMASK=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6)


                          So whatever how many interfaces I'll have and whatever their name, GREP will only grab the first having the MULTICAST option.



                          I use this command to extract only the IP without the mask :



                          IP=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6|cut -d'/' -f1)


                          I use these command on different BDS & NIX it never fail ;)






                          share|improve this answer























                          • If you're going to parse the output of ip, use the -o option.

                            – muru
                            Oct 26 '17 at 8:31



















                          0














                          In my script I'm using something like that:



                          re="inet[[:space:]]+([0-9]+.[0-9]+.[0-9]+.[0-9]+)"
                          if [[ $(ip addr show eth0) =~ $re ]]; then
                          echo $BASH_REMATCH[1]
                          else
                          echo "Cannot determin IP" 1>&2
                          fi


                          It doesn't spawn any process.






                          share|improve this answer
























                            Your Answer








                            StackExchange.ready(function()
                            var channelOptions =
                            tags: "".split(" "),
                            id: "89"
                            ;
                            initTagRenderer("".split(" "), "".split(" "), channelOptions);

                            StackExchange.using("externalEditor", function()
                            // Have to fire editor after snippets, if snippets enabled
                            if (StackExchange.settings.snippets.snippetsEnabled)
                            StackExchange.using("snippets", function()
                            createEditor();
                            );

                            else
                            createEditor();

                            );

                            function createEditor()
                            StackExchange.prepareEditor(
                            heartbeatType: 'answer',
                            autoActivateHeartbeat: false,
                            convertImagesToLinks: true,
                            noModals: true,
                            showLowRepImageUploadWarning: true,
                            reputationToPostImages: 10,
                            bindNavPrevention: true,
                            postfix: "",
                            imageUploader:
                            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                            allowUrls: true
                            ,
                            onDemand: true,
                            discardSelector: ".discard-answer"
                            ,immediatelyShowMarkdownHelp:true
                            );



                            );













                            draft saved

                            draft discarded


















                            StackExchange.ready(
                            function ()
                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f560412%2fdisplaying-ip-address-on-eth0-interface%23new-answer', 'question_page');

                            );

                            Post as a guest















                            Required, but never shown

























                            16 Answers
                            16






                            active

                            oldest

                            votes








                            16 Answers
                            16






                            active

                            oldest

                            votes









                            active

                            oldest

                            votes






                            active

                            oldest

                            votes









                            25














                            save this in a file and then run bash <filename>



                            #!/bin/bash
                            ifconfig eth0 | grep "inet addr"


                            being more accurate to get only number showing IP address:



                            #!/bin/bash
                            ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1


                            Update: If this doesn't works for you, try the other answer






                            share|improve this answer




















                            • 1





                              of course this doesn't work in the latest ubuntu. the latest ifconfig returns "inet <ip>" instead of "inet addr <ip>"

                              – thang
                              Nov 14 '18 at 23:10















                            25














                            save this in a file and then run bash <filename>



                            #!/bin/bash
                            ifconfig eth0 | grep "inet addr"


                            being more accurate to get only number showing IP address:



                            #!/bin/bash
                            ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1


                            Update: If this doesn't works for you, try the other answer






                            share|improve this answer




















                            • 1





                              of course this doesn't work in the latest ubuntu. the latest ifconfig returns "inet <ip>" instead of "inet addr <ip>"

                              – thang
                              Nov 14 '18 at 23:10













                            25












                            25








                            25







                            save this in a file and then run bash <filename>



                            #!/bin/bash
                            ifconfig eth0 | grep "inet addr"


                            being more accurate to get only number showing IP address:



                            #!/bin/bash
                            ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1


                            Update: If this doesn't works for you, try the other answer






                            share|improve this answer















                            save this in a file and then run bash <filename>



                            #!/bin/bash
                            ifconfig eth0 | grep "inet addr"


                            being more accurate to get only number showing IP address:



                            #!/bin/bash
                            ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1


                            Update: If this doesn't works for you, try the other answer







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 18 '18 at 11:14

























                            answered Dec 11 '14 at 23:00









                            Edward TorvaldsEdward Torvalds

                            5,15074079




                            5,15074079







                            • 1





                              of course this doesn't work in the latest ubuntu. the latest ifconfig returns "inet <ip>" instead of "inet addr <ip>"

                              – thang
                              Nov 14 '18 at 23:10












                            • 1





                              of course this doesn't work in the latest ubuntu. the latest ifconfig returns "inet <ip>" instead of "inet addr <ip>"

                              – thang
                              Nov 14 '18 at 23:10







                            1




                            1





                            of course this doesn't work in the latest ubuntu. the latest ifconfig returns "inet <ip>" instead of "inet addr <ip>"

                            – thang
                            Nov 14 '18 at 23:10





                            of course this doesn't work in the latest ubuntu. the latest ifconfig returns "inet <ip>" instead of "inet addr <ip>"

                            – thang
                            Nov 14 '18 at 23:10













                            21














                            For the sake of providing another option, you could use the ip addr command this way to get the IP address:



                            ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1



                            • ip addr show eth0 shows information about eth0


                            • grep "inetb" only shows the line that has the IPv4 address (if you wanted the IPv6 address, change it to "inet6b")


                            • awk 'print $2' prints on the second field, which has the ipaddress/mask, example 172.20.20.15/25


                            • cut -d/ -f1 only takes the IP address portion.

                            In a script:



                            #!/bin/bash
                            theIPaddress=$(ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1)





                            share|improve this answer























                            • this solution actually works!

                              – thang
                              Nov 14 '18 at 23:10















                            21














                            For the sake of providing another option, you could use the ip addr command this way to get the IP address:



                            ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1



                            • ip addr show eth0 shows information about eth0


                            • grep "inetb" only shows the line that has the IPv4 address (if you wanted the IPv6 address, change it to "inet6b")


                            • awk 'print $2' prints on the second field, which has the ipaddress/mask, example 172.20.20.15/25


                            • cut -d/ -f1 only takes the IP address portion.

                            In a script:



                            #!/bin/bash
                            theIPaddress=$(ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1)





                            share|improve this answer























                            • this solution actually works!

                              – thang
                              Nov 14 '18 at 23:10













                            21












                            21








                            21







                            For the sake of providing another option, you could use the ip addr command this way to get the IP address:



                            ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1



                            • ip addr show eth0 shows information about eth0


                            • grep "inetb" only shows the line that has the IPv4 address (if you wanted the IPv6 address, change it to "inet6b")


                            • awk 'print $2' prints on the second field, which has the ipaddress/mask, example 172.20.20.15/25


                            • cut -d/ -f1 only takes the IP address portion.

                            In a script:



                            #!/bin/bash
                            theIPaddress=$(ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1)





                            share|improve this answer













                            For the sake of providing another option, you could use the ip addr command this way to get the IP address:



                            ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1



                            • ip addr show eth0 shows information about eth0


                            • grep "inetb" only shows the line that has the IPv4 address (if you wanted the IPv6 address, change it to "inet6b")


                            • awk 'print $2' prints on the second field, which has the ipaddress/mask, example 172.20.20.15/25


                            • cut -d/ -f1 only takes the IP address portion.

                            In a script:



                            #!/bin/bash
                            theIPaddress=$(ip addr show eth0 | grep "inetb" | awk 'print $2' | cut -d/ -f1)






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 12 '14 at 2:16









                            Alaa AliAlaa Ali

                            22.4k96994




                            22.4k96994












                            • this solution actually works!

                              – thang
                              Nov 14 '18 at 23:10

















                            • this solution actually works!

                              – thang
                              Nov 14 '18 at 23:10
















                            this solution actually works!

                            – thang
                            Nov 14 '18 at 23:10





                            this solution actually works!

                            – thang
                            Nov 14 '18 at 23:10











                            16














                            Taken from https://stackoverflow.com/a/14910952/1695680



                            hostname -i


                            However that may return a local ip address (127.0.0.1), so you may have to use, and filter:



                            hostname -I


                            From hostname's manpages:




                            -i, --ip-address



                            Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses instead.



                            -I, --all-ip-addresses



                            Display all network addresses of the host. This option enumerates all configured addresses on all network inter‐faces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this option does not depend on name resolution. Do not make any assumptions about the order of the output.







                            share|improve this answer

























                            • for the record, I like ip addr show label 'enp*' better, but I is annoying parse, something like ip addr show label 'enp*' | grep -oP inet \S+ | cut -d' ' -f2 can work... how pretty

                              – ThorSummoner
                              Nov 20 '18 at 23:37















                            16














                            Taken from https://stackoverflow.com/a/14910952/1695680



                            hostname -i


                            However that may return a local ip address (127.0.0.1), so you may have to use, and filter:



                            hostname -I


                            From hostname's manpages:




                            -i, --ip-address



                            Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses instead.



                            -I, --all-ip-addresses



                            Display all network addresses of the host. This option enumerates all configured addresses on all network inter‐faces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this option does not depend on name resolution. Do not make any assumptions about the order of the output.







                            share|improve this answer

























                            • for the record, I like ip addr show label 'enp*' better, but I is annoying parse, something like ip addr show label 'enp*' | grep -oP inet \S+ | cut -d' ' -f2 can work... how pretty

                              – ThorSummoner
                              Nov 20 '18 at 23:37













                            16












                            16








                            16







                            Taken from https://stackoverflow.com/a/14910952/1695680



                            hostname -i


                            However that may return a local ip address (127.0.0.1), so you may have to use, and filter:



                            hostname -I


                            From hostname's manpages:




                            -i, --ip-address



                            Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses instead.



                            -I, --all-ip-addresses



                            Display all network addresses of the host. This option enumerates all configured addresses on all network inter‐faces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this option does not depend on name resolution. Do not make any assumptions about the order of the output.







                            share|improve this answer















                            Taken from https://stackoverflow.com/a/14910952/1695680



                            hostname -i


                            However that may return a local ip address (127.0.0.1), so you may have to use, and filter:



                            hostname -I


                            From hostname's manpages:




                            -i, --ip-address



                            Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses instead.



                            -I, --all-ip-addresses



                            Display all network addresses of the host. This option enumerates all configured addresses on all network inter‐faces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this option does not depend on name resolution. Do not make any assumptions about the order of the output.








                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited May 23 '17 at 12:39









                            Community

                            1




                            1










                            answered Mar 9 '16 at 20:01









                            ThorSummonerThorSummoner

                            1,5061325




                            1,5061325












                            • for the record, I like ip addr show label 'enp*' better, but I is annoying parse, something like ip addr show label 'enp*' | grep -oP inet \S+ | cut -d' ' -f2 can work... how pretty

                              – ThorSummoner
                              Nov 20 '18 at 23:37

















                            • for the record, I like ip addr show label 'enp*' better, but I is annoying parse, something like ip addr show label 'enp*' | grep -oP inet \S+ | cut -d' ' -f2 can work... how pretty

                              – ThorSummoner
                              Nov 20 '18 at 23:37
















                            for the record, I like ip addr show label 'enp*' better, but I is annoying parse, something like ip addr show label 'enp*' | grep -oP inet \S+ | cut -d' ' -f2 can work... how pretty

                            – ThorSummoner
                            Nov 20 '18 at 23:37





                            for the record, I like ip addr show label 'enp*' better, but I is annoying parse, something like ip addr show label 'enp*' | grep -oP inet \S+ | cut -d' ' -f2 can work... how pretty

                            – ThorSummoner
                            Nov 20 '18 at 23:37











                            4














                            @markus-lindberg 's response is my favourite. If you add -o -4 to ip's flags then you get a much more easily parsable (and consistent) output:



                            ip -o -4 a | awk '$2 == "eth0" gsub(//.*/, "", $4); print $4 '


                            -o stands for --oneline, which is meant to help in exactly this kind of situations. The -4 is added to limit to the IPv4 address, which is what all the other responses imply.






                            share|improve this answer























                            • Love the ip flags. Using cut rather than advanced awk wizardry: ip -o -4 addr show eth0 scope global | awk 'print $4;' | cut -d/ -f 1

                              – DuffJ
                              Dec 16 '16 at 14:03











                            • @DuffJ it's probably down to a matter of personal taste. I "discovered" cut way after I learned about awk, and I like minimising the number of commands on my pipelines. Nice suggestion in any case.

                              – Amos Shapira
                              Dec 17 '16 at 6:55











                            • I completely agree, Amos. Thanks for your solution!

                              – DuffJ
                              Dec 19 '16 at 12:34















                            4














                            @markus-lindberg 's response is my favourite. If you add -o -4 to ip's flags then you get a much more easily parsable (and consistent) output:



                            ip -o -4 a | awk '$2 == "eth0" gsub(//.*/, "", $4); print $4 '


                            -o stands for --oneline, which is meant to help in exactly this kind of situations. The -4 is added to limit to the IPv4 address, which is what all the other responses imply.






                            share|improve this answer























                            • Love the ip flags. Using cut rather than advanced awk wizardry: ip -o -4 addr show eth0 scope global | awk 'print $4;' | cut -d/ -f 1

                              – DuffJ
                              Dec 16 '16 at 14:03











                            • @DuffJ it's probably down to a matter of personal taste. I "discovered" cut way after I learned about awk, and I like minimising the number of commands on my pipelines. Nice suggestion in any case.

                              – Amos Shapira
                              Dec 17 '16 at 6:55











                            • I completely agree, Amos. Thanks for your solution!

                              – DuffJ
                              Dec 19 '16 at 12:34













                            4












                            4








                            4







                            @markus-lindberg 's response is my favourite. If you add -o -4 to ip's flags then you get a much more easily parsable (and consistent) output:



                            ip -o -4 a | awk '$2 == "eth0" gsub(//.*/, "", $4); print $4 '


                            -o stands for --oneline, which is meant to help in exactly this kind of situations. The -4 is added to limit to the IPv4 address, which is what all the other responses imply.






                            share|improve this answer













                            @markus-lindberg 's response is my favourite. If you add -o -4 to ip's flags then you get a much more easily parsable (and consistent) output:



                            ip -o -4 a | awk '$2 == "eth0" gsub(//.*/, "", $4); print $4 '


                            -o stands for --oneline, which is meant to help in exactly this kind of situations. The -4 is added to limit to the IPv4 address, which is what all the other responses imply.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jun 14 '16 at 1:43









                            Amos ShapiraAmos Shapira

                            183310




                            183310












                            • Love the ip flags. Using cut rather than advanced awk wizardry: ip -o -4 addr show eth0 scope global | awk 'print $4;' | cut -d/ -f 1

                              – DuffJ
                              Dec 16 '16 at 14:03











                            • @DuffJ it's probably down to a matter of personal taste. I "discovered" cut way after I learned about awk, and I like minimising the number of commands on my pipelines. Nice suggestion in any case.

                              – Amos Shapira
                              Dec 17 '16 at 6:55











                            • I completely agree, Amos. Thanks for your solution!

                              – DuffJ
                              Dec 19 '16 at 12:34

















                            • Love the ip flags. Using cut rather than advanced awk wizardry: ip -o -4 addr show eth0 scope global | awk 'print $4;' | cut -d/ -f 1

                              – DuffJ
                              Dec 16 '16 at 14:03











                            • @DuffJ it's probably down to a matter of personal taste. I "discovered" cut way after I learned about awk, and I like minimising the number of commands on my pipelines. Nice suggestion in any case.

                              – Amos Shapira
                              Dec 17 '16 at 6:55











                            • I completely agree, Amos. Thanks for your solution!

                              – DuffJ
                              Dec 19 '16 at 12:34
















                            Love the ip flags. Using cut rather than advanced awk wizardry: ip -o -4 addr show eth0 scope global | awk 'print $4;' | cut -d/ -f 1

                            – DuffJ
                            Dec 16 '16 at 14:03





                            Love the ip flags. Using cut rather than advanced awk wizardry: ip -o -4 addr show eth0 scope global | awk 'print $4;' | cut -d/ -f 1

                            – DuffJ
                            Dec 16 '16 at 14:03













                            @DuffJ it's probably down to a matter of personal taste. I "discovered" cut way after I learned about awk, and I like minimising the number of commands on my pipelines. Nice suggestion in any case.

                            – Amos Shapira
                            Dec 17 '16 at 6:55





                            @DuffJ it's probably down to a matter of personal taste. I "discovered" cut way after I learned about awk, and I like minimising the number of commands on my pipelines. Nice suggestion in any case.

                            – Amos Shapira
                            Dec 17 '16 at 6:55













                            I completely agree, Amos. Thanks for your solution!

                            – DuffJ
                            Dec 19 '16 at 12:34





                            I completely agree, Amos. Thanks for your solution!

                            – DuffJ
                            Dec 19 '16 at 12:34











                            3














                            Here are some oneliners.....



                            Awk



                            ifconfig eth0 | awk '/inet addr/split($2,a,":"); print a[2]'


                            split function in the above awk command splits the second column based on the delimiter : and stores the splitted value into an associative array a. So a[2] holds the value of the second part.



                            sed



                            ifconfig eth0 | sed -n '/inet addr/s/.*inet addr: *([^[:space:]]+).*/1/p'


                            In basic sed , (...) called capturing group which is used to capture the characters. We could refer those captured characters through back-referencing. ([^[:space:]]+) captures any character but not space one or more times.



                            grep



                            ifconfig eth0 | grep -oP 'inet addr:KS+'


                            K discards the previously matched characters from printing at the final and S+ matches one or more non-space characters.



                            Perl



                            ifconfig eth0 | perl -lane 'print $1 if /inet addr:(S+)/'


                            One or more non-space characters which are next to the inet addr: string are captured and finally we print those captured characters only.






                            share|improve this answer

























                            • @edwardtorvalds added some explanation. I think this would be helpful for future readers. Feel free to ask any questions from the above commands... :)

                              – Avinash Raj
                              Dec 12 '14 at 8:07















                            3














                            Here are some oneliners.....



                            Awk



                            ifconfig eth0 | awk '/inet addr/split($2,a,":"); print a[2]'


                            split function in the above awk command splits the second column based on the delimiter : and stores the splitted value into an associative array a. So a[2] holds the value of the second part.



                            sed



                            ifconfig eth0 | sed -n '/inet addr/s/.*inet addr: *([^[:space:]]+).*/1/p'


                            In basic sed , (...) called capturing group which is used to capture the characters. We could refer those captured characters through back-referencing. ([^[:space:]]+) captures any character but not space one or more times.



                            grep



                            ifconfig eth0 | grep -oP 'inet addr:KS+'


                            K discards the previously matched characters from printing at the final and S+ matches one or more non-space characters.



                            Perl



                            ifconfig eth0 | perl -lane 'print $1 if /inet addr:(S+)/'


                            One or more non-space characters which are next to the inet addr: string are captured and finally we print those captured characters only.






                            share|improve this answer

























                            • @edwardtorvalds added some explanation. I think this would be helpful for future readers. Feel free to ask any questions from the above commands... :)

                              – Avinash Raj
                              Dec 12 '14 at 8:07













                            3












                            3








                            3







                            Here are some oneliners.....



                            Awk



                            ifconfig eth0 | awk '/inet addr/split($2,a,":"); print a[2]'


                            split function in the above awk command splits the second column based on the delimiter : and stores the splitted value into an associative array a. So a[2] holds the value of the second part.



                            sed



                            ifconfig eth0 | sed -n '/inet addr/s/.*inet addr: *([^[:space:]]+).*/1/p'


                            In basic sed , (...) called capturing group which is used to capture the characters. We could refer those captured characters through back-referencing. ([^[:space:]]+) captures any character but not space one or more times.



                            grep



                            ifconfig eth0 | grep -oP 'inet addr:KS+'


                            K discards the previously matched characters from printing at the final and S+ matches one or more non-space characters.



                            Perl



                            ifconfig eth0 | perl -lane 'print $1 if /inet addr:(S+)/'


                            One or more non-space characters which are next to the inet addr: string are captured and finally we print those captured characters only.






                            share|improve this answer















                            Here are some oneliners.....



                            Awk



                            ifconfig eth0 | awk '/inet addr/split($2,a,":"); print a[2]'


                            split function in the above awk command splits the second column based on the delimiter : and stores the splitted value into an associative array a. So a[2] holds the value of the second part.



                            sed



                            ifconfig eth0 | sed -n '/inet addr/s/.*inet addr: *([^[:space:]]+).*/1/p'


                            In basic sed , (...) called capturing group which is used to capture the characters. We could refer those captured characters through back-referencing. ([^[:space:]]+) captures any character but not space one or more times.



                            grep



                            ifconfig eth0 | grep -oP 'inet addr:KS+'


                            K discards the previously matched characters from printing at the final and S+ matches one or more non-space characters.



                            Perl



                            ifconfig eth0 | perl -lane 'print $1 if /inet addr:(S+)/'


                            One or more non-space characters which are next to the inet addr: string are captured and finally we print those captured characters only.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Dec 12 '14 at 8:07

























                            answered Dec 12 '14 at 7:28









                            Avinash RajAvinash Raj

                            52.3k41168219




                            52.3k41168219












                            • @edwardtorvalds added some explanation. I think this would be helpful for future readers. Feel free to ask any questions from the above commands... :)

                              – Avinash Raj
                              Dec 12 '14 at 8:07

















                            • @edwardtorvalds added some explanation. I think this would be helpful for future readers. Feel free to ask any questions from the above commands... :)

                              – Avinash Raj
                              Dec 12 '14 at 8:07
















                            @edwardtorvalds added some explanation. I think this would be helpful for future readers. Feel free to ask any questions from the above commands... :)

                            – Avinash Raj
                            Dec 12 '14 at 8:07





                            @edwardtorvalds added some explanation. I think this would be helpful for future readers. Feel free to ask any questions from the above commands... :)

                            – Avinash Raj
                            Dec 12 '14 at 8:07











                            1














                            I suggest using a python library like netifaces that is specifically designed for this purpose.



                            sudo pip install netifaces
                            python -c "import netifaces; print netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']"


                            To obtain the default network interface that is in use.



                            default_inf = netifaces.gateways()['default'][netifaces.AF_INET][1]





                            share|improve this answer





























                              1














                              I suggest using a python library like netifaces that is specifically designed for this purpose.



                              sudo pip install netifaces
                              python -c "import netifaces; print netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']"


                              To obtain the default network interface that is in use.



                              default_inf = netifaces.gateways()['default'][netifaces.AF_INET][1]





                              share|improve this answer



























                                1












                                1








                                1







                                I suggest using a python library like netifaces that is specifically designed for this purpose.



                                sudo pip install netifaces
                                python -c "import netifaces; print netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']"


                                To obtain the default network interface that is in use.



                                default_inf = netifaces.gateways()['default'][netifaces.AF_INET][1]





                                share|improve this answer















                                I suggest using a python library like netifaces that is specifically designed for this purpose.



                                sudo pip install netifaces
                                python -c "import netifaces; print netifaces.ifaddresses('eth0')[netifaces.AF_INET][0]['addr']"


                                To obtain the default network interface that is in use.



                                default_inf = netifaces.gateways()['default'][netifaces.AF_INET][1]






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Apr 10 '16 at 18:59

























                                answered Apr 9 '16 at 0:34









                                SandeepSandeep

                                38234




                                38234





















                                    1














                                    ip addr|awk '/eth0/ && /inet/ gsub(//[0-9][0-9]/,""); print $2'


                                    This only use ip addr which is a replacement for ifconfig and awk combined with substitution (gsub).



                                    Stop using too many processes for simple tasks






                                    share|improve this answer





























                                      1














                                      ip addr|awk '/eth0/ && /inet/ gsub(//[0-9][0-9]/,""); print $2'


                                      This only use ip addr which is a replacement for ifconfig and awk combined with substitution (gsub).



                                      Stop using too many processes for simple tasks






                                      share|improve this answer



























                                        1












                                        1








                                        1







                                        ip addr|awk '/eth0/ && /inet/ gsub(//[0-9][0-9]/,""); print $2'


                                        This only use ip addr which is a replacement for ifconfig and awk combined with substitution (gsub).



                                        Stop using too many processes for simple tasks






                                        share|improve this answer















                                        ip addr|awk '/eth0/ && /inet/ gsub(//[0-9][0-9]/,""); print $2'


                                        This only use ip addr which is a replacement for ifconfig and awk combined with substitution (gsub).



                                        Stop using too many processes for simple tasks







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jun 14 '16 at 2:19









                                        muru

                                        1




                                        1










                                        answered Oct 23 '15 at 8:42









                                        Markus LindbergMarkus Lindberg

                                        1215




                                        1215





















                                            1














                                            Just one more option that can be useful if you don't have awk (as it is the case in some embedded devices):



                                            ip addr show dev eth0 scope global | grep "inetb" | cut -d/ -f 1 | egrep -o "([[:digit:]]1,3[.]1)3[[:digit:]]1,3"





                                            share|improve this answer



























                                              1














                                              Just one more option that can be useful if you don't have awk (as it is the case in some embedded devices):



                                              ip addr show dev eth0 scope global | grep "inetb" | cut -d/ -f 1 | egrep -o "([[:digit:]]1,3[.]1)3[[:digit:]]1,3"





                                              share|improve this answer

























                                                1












                                                1








                                                1







                                                Just one more option that can be useful if you don't have awk (as it is the case in some embedded devices):



                                                ip addr show dev eth0 scope global | grep "inetb" | cut -d/ -f 1 | egrep -o "([[:digit:]]1,3[.]1)3[[:digit:]]1,3"





                                                share|improve this answer













                                                Just one more option that can be useful if you don't have awk (as it is the case in some embedded devices):



                                                ip addr show dev eth0 scope global | grep "inetb" | cut -d/ -f 1 | egrep -o "([[:digit:]]1,3[.]1)3[[:digit:]]1,3"






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Aug 2 '16 at 12:43









                                                Fulvio FlacoFulvio Flaco

                                                111




                                                111





















                                                    1














                                                    Here's a good one, only uses grep as secondary command:



                                                    ip addr show eth0 | grep -oP 'inet KS[0-9.]+'



                                                    I don't see why you should use more commands than needed






                                                    share|improve this answer



























                                                      1














                                                      Here's a good one, only uses grep as secondary command:



                                                      ip addr show eth0 | grep -oP 'inet KS[0-9.]+'



                                                      I don't see why you should use more commands than needed






                                                      share|improve this answer

























                                                        1












                                                        1








                                                        1







                                                        Here's a good one, only uses grep as secondary command:



                                                        ip addr show eth0 | grep -oP 'inet KS[0-9.]+'



                                                        I don't see why you should use more commands than needed






                                                        share|improve this answer













                                                        Here's a good one, only uses grep as secondary command:



                                                        ip addr show eth0 | grep -oP 'inet KS[0-9.]+'



                                                        I don't see why you should use more commands than needed







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Jul 18 '17 at 19:10









                                                        RickRick

                                                        111




                                                        111





















                                                            1














                                                            ifconfig eth0|grep 'inet '|awk 'print $2'






                                                            share|improve this answer



























                                                              1














                                                              ifconfig eth0|grep 'inet '|awk 'print $2'






                                                              share|improve this answer

























                                                                1












                                                                1








                                                                1







                                                                ifconfig eth0|grep 'inet '|awk 'print $2'






                                                                share|improve this answer













                                                                ifconfig eth0|grep 'inet '|awk 'print $2'







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered Nov 10 '17 at 20:58









                                                                Maksim KostrominMaksim Kostromin

                                                                1112




                                                                1112





















                                                                    1














                                                                    here's for IPv4:



                                                                    ip -f inet a|grep -oP "(?<=inet ).+(?=/)"



                                                                    here's for IPv4 & particular dev (eth0):



                                                                    ip -f inet a show eth0|grep -oP "(?<=inet ).+(?=/)"



                                                                    for IPv6:



                                                                    ip -6 -o a|grep -oP "(?<=inet6 ).+(?=/)"






                                                                    share|improve this answer



























                                                                      1














                                                                      here's for IPv4:



                                                                      ip -f inet a|grep -oP "(?<=inet ).+(?=/)"



                                                                      here's for IPv4 & particular dev (eth0):



                                                                      ip -f inet a show eth0|grep -oP "(?<=inet ).+(?=/)"



                                                                      for IPv6:



                                                                      ip -6 -o a|grep -oP "(?<=inet6 ).+(?=/)"






                                                                      share|improve this answer

























                                                                        1












                                                                        1








                                                                        1







                                                                        here's for IPv4:



                                                                        ip -f inet a|grep -oP "(?<=inet ).+(?=/)"



                                                                        here's for IPv4 & particular dev (eth0):



                                                                        ip -f inet a show eth0|grep -oP "(?<=inet ).+(?=/)"



                                                                        for IPv6:



                                                                        ip -6 -o a|grep -oP "(?<=inet6 ).+(?=/)"






                                                                        share|improve this answer













                                                                        here's for IPv4:



                                                                        ip -f inet a|grep -oP "(?<=inet ).+(?=/)"



                                                                        here's for IPv4 & particular dev (eth0):



                                                                        ip -f inet a show eth0|grep -oP "(?<=inet ).+(?=/)"



                                                                        for IPv6:



                                                                        ip -6 -o a|grep -oP "(?<=inet6 ).+(?=/)"







                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Feb 13 '18 at 12:04









                                                                        XXLXXL

                                                                        1112




                                                                        1112





















                                                                            1














                                                                            You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                                                                            If you want the IPv4 address for your Ethernet interface eth0:



                                                                            $ ip -4 -o addr show eth0 | awk 'print $4'
                                                                            192.168.1.166/24


                                                                            As a script:



                                                                            $ INTFC=eth0 
                                                                            $ MYIPV4=$(ip -4 -o addr show $INTFC | awk 'print $4')
                                                                            $ echo $MYIPV4
                                                                            192.168.1.166/24



                                                                            The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                                                                            $ ip -4 -o addr show eth0 | awk 'print $4' | cut -d "/" -f 1 
                                                                            192.168.1.166


                                                                            Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                                                                            $ ip route get 8.8.8.8 | awk ' print $NF; exit '
                                                                            192.168.1.166


                                                                            As a script:



                                                                            $ RHOST=8.8.8.8 
                                                                            $ MYIP=$(ip route get $RHOST | awk ' print $NF; exit ')
                                                                            $ echo $MYIP
                                                                            192.168.1.166


                                                                            This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                                                                            While ip would be my preferred approach, it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                                                                            $ hostname --all-ip-addresses | awk 'print $1' 


                                                                            Or, if you want the IPv6 address:



                                                                            $ hostname --all-ip-addresses | awk 'print $2' 


                                                                            As a script:



                                                                            $ MYV4IP=$(hostname --all-ip-addresses | awk 'print $1') 
                                                                            $ MYV6IP=$(hostname --all-ip-addresses | awk 'print $2')
                                                                            $ echo $MYV4IP
                                                                            192.168.1.166
                                                                            $ echo $MYV6IP
                                                                            2601:7c1:103:b27:352e:e151:c7d8:3379





                                                                            share|improve this answer



























                                                                              1














                                                                              You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                                                                              If you want the IPv4 address for your Ethernet interface eth0:



                                                                              $ ip -4 -o addr show eth0 | awk 'print $4'
                                                                              192.168.1.166/24


                                                                              As a script:



                                                                              $ INTFC=eth0 
                                                                              $ MYIPV4=$(ip -4 -o addr show $INTFC | awk 'print $4')
                                                                              $ echo $MYIPV4
                                                                              192.168.1.166/24



                                                                              The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                                                                              $ ip -4 -o addr show eth0 | awk 'print $4' | cut -d "/" -f 1 
                                                                              192.168.1.166


                                                                              Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                                                                              $ ip route get 8.8.8.8 | awk ' print $NF; exit '
                                                                              192.168.1.166


                                                                              As a script:



                                                                              $ RHOST=8.8.8.8 
                                                                              $ MYIP=$(ip route get $RHOST | awk ' print $NF; exit ')
                                                                              $ echo $MYIP
                                                                              192.168.1.166


                                                                              This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                                                                              While ip would be my preferred approach, it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                                                                              $ hostname --all-ip-addresses | awk 'print $1' 


                                                                              Or, if you want the IPv6 address:



                                                                              $ hostname --all-ip-addresses | awk 'print $2' 


                                                                              As a script:



                                                                              $ MYV4IP=$(hostname --all-ip-addresses | awk 'print $1') 
                                                                              $ MYV6IP=$(hostname --all-ip-addresses | awk 'print $2')
                                                                              $ echo $MYV4IP
                                                                              192.168.1.166
                                                                              $ echo $MYV6IP
                                                                              2601:7c1:103:b27:352e:e151:c7d8:3379





                                                                              share|improve this answer

























                                                                                1












                                                                                1








                                                                                1







                                                                                You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                                                                                If you want the IPv4 address for your Ethernet interface eth0:



                                                                                $ ip -4 -o addr show eth0 | awk 'print $4'
                                                                                192.168.1.166/24


                                                                                As a script:



                                                                                $ INTFC=eth0 
                                                                                $ MYIPV4=$(ip -4 -o addr show $INTFC | awk 'print $4')
                                                                                $ echo $MYIPV4
                                                                                192.168.1.166/24



                                                                                The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                                                                                $ ip -4 -o addr show eth0 | awk 'print $4' | cut -d "/" -f 1 
                                                                                192.168.1.166


                                                                                Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                                                                                $ ip route get 8.8.8.8 | awk ' print $NF; exit '
                                                                                192.168.1.166


                                                                                As a script:



                                                                                $ RHOST=8.8.8.8 
                                                                                $ MYIP=$(ip route get $RHOST | awk ' print $NF; exit ')
                                                                                $ echo $MYIP
                                                                                192.168.1.166


                                                                                This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                                                                                While ip would be my preferred approach, it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                                                                                $ hostname --all-ip-addresses | awk 'print $1' 


                                                                                Or, if you want the IPv6 address:



                                                                                $ hostname --all-ip-addresses | awk 'print $2' 


                                                                                As a script:



                                                                                $ MYV4IP=$(hostname --all-ip-addresses | awk 'print $1') 
                                                                                $ MYV6IP=$(hostname --all-ip-addresses | awk 'print $2')
                                                                                $ echo $MYV4IP
                                                                                192.168.1.166
                                                                                $ echo $MYV6IP
                                                                                2601:7c1:103:b27:352e:e151:c7d8:3379





                                                                                share|improve this answer













                                                                                You should use ip (instead of ifconfig) as it's current, maintained, and perhaps most importantly for scripting purposes, it produces a consistent & parsable output. Following are a few similar approaches:



                                                                                If you want the IPv4 address for your Ethernet interface eth0:



                                                                                $ ip -4 -o addr show eth0 | awk 'print $4'
                                                                                192.168.1.166/24


                                                                                As a script:



                                                                                $ INTFC=eth0 
                                                                                $ MYIPV4=$(ip -4 -o addr show $INTFC | awk 'print $4')
                                                                                $ echo $MYIPV4
                                                                                192.168.1.166/24



                                                                                The output produced above is in CIDR notation. If CIDR notation isn't wanted, it can be stripped:



                                                                                $ ip -4 -o addr show eth0 | awk 'print $4' | cut -d "/" -f 1 
                                                                                192.168.1.166


                                                                                Another option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:



                                                                                $ ip route get 8.8.8.8 | awk ' print $NF; exit '
                                                                                192.168.1.166


                                                                                As a script:



                                                                                $ RHOST=8.8.8.8 
                                                                                $ MYIP=$(ip route get $RHOST | awk ' print $NF; exit ')
                                                                                $ echo $MYIP
                                                                                192.168.1.166


                                                                                This works perfectly well on a host with a single interface, but more advantageously will also work on hosts with multiple interfaces and/or route specifications.



                                                                                While ip would be my preferred approach, it's certainly not the only way to skin this cat. Here's another approach that uses hostname if you prefer something easier/more concise:



                                                                                $ hostname --all-ip-addresses | awk 'print $1' 


                                                                                Or, if you want the IPv6 address:



                                                                                $ hostname --all-ip-addresses | awk 'print $2' 


                                                                                As a script:



                                                                                $ MYV4IP=$(hostname --all-ip-addresses | awk 'print $1') 
                                                                                $ MYV6IP=$(hostname --all-ip-addresses | awk 'print $2')
                                                                                $ echo $MYV4IP
                                                                                192.168.1.166
                                                                                $ echo $MYV6IP
                                                                                2601:7c1:103:b27:352e:e151:c7d8:3379






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered 6 hours ago









                                                                                SeamusSeamus

                                                                                1463




                                                                                1463





















                                                                                    0














                                                                                    this can be used with a normal user too.



                                                                                    ip addr show eth0 | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6





                                                                                    share|improve this answer

























                                                                                    • he ask for eth0, this version of your script could help (also show loopback tho) ip addr show | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6

                                                                                      – TiloBunt
                                                                                      Mar 25 '17 at 17:01












                                                                                    • This is pretty much the same answer as askubuntu.com/a/560466/367990, just using cut twice instead of a combination of awk and cut to parse the output. Next time you should better check out all other answers first and ensure you don't post a duplicate solution. In this case here, I think it's arguable whether it's a duplicate or just similar, so please take it as a general hint. Thanks.

                                                                                      – Byte Commander
                                                                                      Jul 7 '17 at 19:49















                                                                                    0














                                                                                    this can be used with a normal user too.



                                                                                    ip addr show eth0 | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6





                                                                                    share|improve this answer

























                                                                                    • he ask for eth0, this version of your script could help (also show loopback tho) ip addr show | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6

                                                                                      – TiloBunt
                                                                                      Mar 25 '17 at 17:01












                                                                                    • This is pretty much the same answer as askubuntu.com/a/560466/367990, just using cut twice instead of a combination of awk and cut to parse the output. Next time you should better check out all other answers first and ensure you don't post a duplicate solution. In this case here, I think it's arguable whether it's a duplicate or just similar, so please take it as a general hint. Thanks.

                                                                                      – Byte Commander
                                                                                      Jul 7 '17 at 19:49













                                                                                    0












                                                                                    0








                                                                                    0







                                                                                    this can be used with a normal user too.



                                                                                    ip addr show eth0 | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6





                                                                                    share|improve this answer















                                                                                    this can be used with a normal user too.



                                                                                    ip addr show eth0 | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6






                                                                                    share|improve this answer














                                                                                    share|improve this answer



                                                                                    share|improve this answer








                                                                                    edited Jul 7 '17 at 19:27

























                                                                                    answered Mar 24 '17 at 19:34









                                                                                    Matheus BaldassoMatheus Baldasso

                                                                                    11




                                                                                    11












                                                                                    • he ask for eth0, this version of your script could help (also show loopback tho) ip addr show | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6

                                                                                      – TiloBunt
                                                                                      Mar 25 '17 at 17:01












                                                                                    • This is pretty much the same answer as askubuntu.com/a/560466/367990, just using cut twice instead of a combination of awk and cut to parse the output. Next time you should better check out all other answers first and ensure you don't post a duplicate solution. In this case here, I think it's arguable whether it's a duplicate or just similar, so please take it as a general hint. Thanks.

                                                                                      – Byte Commander
                                                                                      Jul 7 '17 at 19:49

















                                                                                    • he ask for eth0, this version of your script could help (also show loopback tho) ip addr show | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6

                                                                                      – TiloBunt
                                                                                      Mar 25 '17 at 17:01












                                                                                    • This is pretty much the same answer as askubuntu.com/a/560466/367990, just using cut twice instead of a combination of awk and cut to parse the output. Next time you should better check out all other answers first and ensure you don't post a duplicate solution. In this case here, I think it's arguable whether it's a duplicate or just similar, so please take it as a general hint. Thanks.

                                                                                      – Byte Commander
                                                                                      Jul 7 '17 at 19:49
















                                                                                    he ask for eth0, this version of your script could help (also show loopback tho) ip addr show | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6

                                                                                    – TiloBunt
                                                                                    Mar 25 '17 at 17:01






                                                                                    he ask for eth0, this version of your script could help (also show loopback tho) ip addr show | grep "inet " | cut -d '/' -f1 | cut -d ' ' -f6

                                                                                    – TiloBunt
                                                                                    Mar 25 '17 at 17:01














                                                                                    This is pretty much the same answer as askubuntu.com/a/560466/367990, just using cut twice instead of a combination of awk and cut to parse the output. Next time you should better check out all other answers first and ensure you don't post a duplicate solution. In this case here, I think it's arguable whether it's a duplicate or just similar, so please take it as a general hint. Thanks.

                                                                                    – Byte Commander
                                                                                    Jul 7 '17 at 19:49





                                                                                    This is pretty much the same answer as askubuntu.com/a/560466/367990, just using cut twice instead of a combination of awk and cut to parse the output. Next time you should better check out all other answers first and ensure you don't post a duplicate solution. In this case here, I think it's arguable whether it's a duplicate or just similar, so please take it as a general hint. Thanks.

                                                                                    – Byte Commander
                                                                                    Jul 7 '17 at 19:49











                                                                                    0














                                                                                    This is the shortest way I could find:



                                                                                    ip -f inet addr show $1 | grep -Po 'inet K[d.]+'



                                                                                    Replace $1 with your network interface.



                                                                                    ip -f inet tells ip to only return values for the inet (ipv4) family.



                                                                                    grep -Po tells grep to interperate the next value as a perl-regex, and only print the matching values.



                                                                                    The regex K[d.]+ says "throw away everything up to this point (K), and match as many numeric values followed by a dot in a row as possible". This will therefore only match the IP address and ignore everything after it, including the shortform XX subnet mask.






                                                                                    share|improve this answer





























                                                                                      0














                                                                                      This is the shortest way I could find:



                                                                                      ip -f inet addr show $1 | grep -Po 'inet K[d.]+'



                                                                                      Replace $1 with your network interface.



                                                                                      ip -f inet tells ip to only return values for the inet (ipv4) family.



                                                                                      grep -Po tells grep to interperate the next value as a perl-regex, and only print the matching values.



                                                                                      The regex K[d.]+ says "throw away everything up to this point (K), and match as many numeric values followed by a dot in a row as possible". This will therefore only match the IP address and ignore everything after it, including the shortform XX subnet mask.






                                                                                      share|improve this answer



























                                                                                        0












                                                                                        0








                                                                                        0







                                                                                        This is the shortest way I could find:



                                                                                        ip -f inet addr show $1 | grep -Po 'inet K[d.]+'



                                                                                        Replace $1 with your network interface.



                                                                                        ip -f inet tells ip to only return values for the inet (ipv4) family.



                                                                                        grep -Po tells grep to interperate the next value as a perl-regex, and only print the matching values.



                                                                                        The regex K[d.]+ says "throw away everything up to this point (K), and match as many numeric values followed by a dot in a row as possible". This will therefore only match the IP address and ignore everything after it, including the shortform XX subnet mask.






                                                                                        share|improve this answer















                                                                                        This is the shortest way I could find:



                                                                                        ip -f inet addr show $1 | grep -Po 'inet K[d.]+'



                                                                                        Replace $1 with your network interface.



                                                                                        ip -f inet tells ip to only return values for the inet (ipv4) family.



                                                                                        grep -Po tells grep to interperate the next value as a perl-regex, and only print the matching values.



                                                                                        The regex K[d.]+ says "throw away everything up to this point (K), and match as many numeric values followed by a dot in a row as possible". This will therefore only match the IP address and ignore everything after it, including the shortform XX subnet mask.







                                                                                        share|improve this answer














                                                                                        share|improve this answer



                                                                                        share|improve this answer








                                                                                        edited Jul 19 '17 at 6:33

























                                                                                        answered Jul 19 '17 at 6:27









                                                                                        RyanRyan

                                                                                        1113




                                                                                        1113





















                                                                                            0














                                                                                            in these days with multiples interfaces (eg if you use a docker) and naming interface by ETH is not anymore the norms



                                                                                            I use this command to extract the IP/Mask :



                                                                                            IPMASK=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6)


                                                                                            So whatever how many interfaces I'll have and whatever their name, GREP will only grab the first having the MULTICAST option.



                                                                                            I use this command to extract only the IP without the mask :



                                                                                            IP=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6|cut -d'/' -f1)


                                                                                            I use these command on different BDS & NIX it never fail ;)






                                                                                            share|improve this answer























                                                                                            • If you're going to parse the output of ip, use the -o option.

                                                                                              – muru
                                                                                              Oct 26 '17 at 8:31
















                                                                                            0














                                                                                            in these days with multiples interfaces (eg if you use a docker) and naming interface by ETH is not anymore the norms



                                                                                            I use this command to extract the IP/Mask :



                                                                                            IPMASK=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6)


                                                                                            So whatever how many interfaces I'll have and whatever their name, GREP will only grab the first having the MULTICAST option.



                                                                                            I use this command to extract only the IP without the mask :



                                                                                            IP=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6|cut -d'/' -f1)


                                                                                            I use these command on different BDS & NIX it never fail ;)






                                                                                            share|improve this answer























                                                                                            • If you're going to parse the output of ip, use the -o option.

                                                                                              – muru
                                                                                              Oct 26 '17 at 8:31














                                                                                            0












                                                                                            0








                                                                                            0







                                                                                            in these days with multiples interfaces (eg if you use a docker) and naming interface by ETH is not anymore the norms



                                                                                            I use this command to extract the IP/Mask :



                                                                                            IPMASK=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6)


                                                                                            So whatever how many interfaces I'll have and whatever their name, GREP will only grab the first having the MULTICAST option.



                                                                                            I use this command to extract only the IP without the mask :



                                                                                            IP=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6|cut -d'/' -f1)


                                                                                            I use these command on different BDS & NIX it never fail ;)






                                                                                            share|improve this answer













                                                                                            in these days with multiples interfaces (eg if you use a docker) and naming interface by ETH is not anymore the norms



                                                                                            I use this command to extract the IP/Mask :



                                                                                            IPMASK=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6)


                                                                                            So whatever how many interfaces I'll have and whatever their name, GREP will only grab the first having the MULTICAST option.



                                                                                            I use this command to extract only the IP without the mask :



                                                                                            IP=$(ip a s|grep -A8 -m1 MULTICAST|grep -m1 inet|cut -d' ' -f6|cut -d'/' -f1)


                                                                                            I use these command on different BDS & NIX it never fail ;)







                                                                                            share|improve this answer












                                                                                            share|improve this answer



                                                                                            share|improve this answer










                                                                                            answered Oct 26 '17 at 7:28









                                                                                            JOduMonTJOduMonT

                                                                                            194




                                                                                            194












                                                                                            • If you're going to parse the output of ip, use the -o option.

                                                                                              – muru
                                                                                              Oct 26 '17 at 8:31


















                                                                                            • If you're going to parse the output of ip, use the -o option.

                                                                                              – muru
                                                                                              Oct 26 '17 at 8:31

















                                                                                            If you're going to parse the output of ip, use the -o option.

                                                                                            – muru
                                                                                            Oct 26 '17 at 8:31






                                                                                            If you're going to parse the output of ip, use the -o option.

                                                                                            – muru
                                                                                            Oct 26 '17 at 8:31












                                                                                            0














                                                                                            In my script I'm using something like that:



                                                                                            re="inet[[:space:]]+([0-9]+.[0-9]+.[0-9]+.[0-9]+)"
                                                                                            if [[ $(ip addr show eth0) =~ $re ]]; then
                                                                                            echo $BASH_REMATCH[1]
                                                                                            else
                                                                                            echo "Cannot determin IP" 1>&2
                                                                                            fi


                                                                                            It doesn't spawn any process.






                                                                                            share|improve this answer





























                                                                                              0














                                                                                              In my script I'm using something like that:



                                                                                              re="inet[[:space:]]+([0-9]+.[0-9]+.[0-9]+.[0-9]+)"
                                                                                              if [[ $(ip addr show eth0) =~ $re ]]; then
                                                                                              echo $BASH_REMATCH[1]
                                                                                              else
                                                                                              echo "Cannot determin IP" 1>&2
                                                                                              fi


                                                                                              It doesn't spawn any process.






                                                                                              share|improve this answer



























                                                                                                0












                                                                                                0








                                                                                                0







                                                                                                In my script I'm using something like that:



                                                                                                re="inet[[:space:]]+([0-9]+.[0-9]+.[0-9]+.[0-9]+)"
                                                                                                if [[ $(ip addr show eth0) =~ $re ]]; then
                                                                                                echo $BASH_REMATCH[1]
                                                                                                else
                                                                                                echo "Cannot determin IP" 1>&2
                                                                                                fi


                                                                                                It doesn't spawn any process.






                                                                                                share|improve this answer















                                                                                                In my script I'm using something like that:



                                                                                                re="inet[[:space:]]+([0-9]+.[0-9]+.[0-9]+.[0-9]+)"
                                                                                                if [[ $(ip addr show eth0) =~ $re ]]; then
                                                                                                echo $BASH_REMATCH[1]
                                                                                                else
                                                                                                echo "Cannot determin IP" 1>&2
                                                                                                fi


                                                                                                It doesn't spawn any process.







                                                                                                share|improve this answer














                                                                                                share|improve this answer



                                                                                                share|improve this answer








                                                                                                edited Nov 12 '17 at 15:46









                                                                                                derHugo

                                                                                                2,31521531




                                                                                                2,31521531










                                                                                                answered Oct 29 '17 at 18:43









                                                                                                Maciej WawrzyńczukMaciej Wawrzyńczuk

                                                                                                1011




                                                                                                1011



























                                                                                                    draft saved

                                                                                                    draft discarded
















































                                                                                                    Thanks for contributing an answer to Ask Ubuntu!


                                                                                                    • Please be sure to answer the question. Provide details and share your research!

                                                                                                    But avoid


                                                                                                    • Asking for help, clarification, or responding to other answers.

                                                                                                    • Making statements based on opinion; back them up with references or personal experience.

                                                                                                    To learn more, see our tips on writing great answers.




                                                                                                    draft saved


                                                                                                    draft discarded














                                                                                                    StackExchange.ready(
                                                                                                    function ()
                                                                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f560412%2fdisplaying-ip-address-on-eth0-interface%23new-answer', 'question_page');

                                                                                                    );

                                                                                                    Post as a guest















                                                                                                    Required, but never shown





















































                                                                                                    Required, but never shown














                                                                                                    Required, but never shown












                                                                                                    Required, but never shown







                                                                                                    Required, but never shown

































                                                                                                    Required, but never shown














                                                                                                    Required, but never shown












                                                                                                    Required, but never shown







                                                                                                    Required, but never shown







                                                                                                    Popular posts from this blog

                                                                                                    Möglingen Índice Localización Historia Demografía Referencias Enlaces externos Menú de navegación48°53′18″N 9°07′45″E / 48.888333333333, 9.129166666666748°53′18″N 9°07′45″E / 48.888333333333, 9.1291666666667Sitio web oficial Mapa de Möglingen«Gemeinden in Deutschland nach Fläche, Bevölkerung und Postleitzahl am 30.09.2016»Möglingen

                                                                                                    Virtualbox - Configuration error: Querying “UUID” failed (VERR_CFGM_VALUE_NOT_FOUND)“VERR_SUPLIB_WORLD_WRITABLE” error when trying to installing OS in virtualboxVirtual Box Kernel errorFailed to open a seesion for the virtual machineFailed to open a session for the virtual machineUbuntu 14.04 LTS Virtualbox errorcan't use VM VirtualBoxusing virtualboxI can't run Linux-64 Bit on VirtualBoxUnable to insert the virtual optical disk (VBoxguestaddition) in virtual machine for ubuntu server in win 10VirtuaBox in Ubuntu 18.04 Issues with Win10.ISO Installation

                                                                                                    Torre de la Isleta Índice Véase también Referencias Bibliografía Enlaces externos Menú de navegación38°25′58″N 0°23′02″O / 38.43277778, -0.3838888938°25′58″N 0°23′02″O / 38.43277778, -0.38388889Torre de la Illeta de l’Horta o Torre Saleta. Base de datos de bienes inmuebles. Patrimonio Cultural. Secretaría de Estado de CulturaFicha BIC Torre de la Illeta de l’Horta. Dirección General de Patrimonio Cultural. Generalitat ValencianaLugares de interés. Ayuntamiento del CampelloTorre de la Isleta en CastillosNet.org