Press "Enter" to skip to content

Show Public IP in Terminal

Reading Time: 2 minutes

I wanted to display external/public IP address whenever I open terminal, but also add an alias that will allow me to check my public IP from terminal. Here is how to do it.

Add to your ~./bashrc following lines:

#Show public IP address
whatsmyip="$(dig +short"
echo "Your Public IP is: $whatsmyip"

alias whatsmyip="echo 'Your Public IP is: $whatsmyip'"

For ease of use, I stored the output of the command in variable $whatsmyip that I can then make a call to in an alias whatsmyip

Explanation of the command itself

dig (domain information groper) command will query DNS nameserver for information about IP address of given domain. Full syntax for the command is ‘dig name @server type’.

name is the record you want to query
server is the name or IP address of DNS server to query
type is the what type of query you want to look at – it could be ANY, A or MX, if omitted A is used by default
+short is used to get just the answer to the query

So the full command is dig +short is a special domain that sends back the IP address of where the request came from, meaning your own IP. is the DNS server to query, we could also use the IP address –

If we would replace with we would get IP addresses of that domain.

The use of +short is important as we only want to know the answer to the query to then store it in a Bash variable, without it, full returned query looks like this:

; <<>> DiG 9.11.3-1ubuntu1.3-Ubuntu <<>>
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 20980
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

; EDNS: version: 0, flags:; udp: 4096
;		IN	A


;; Query time: 13 msec
;; WHEN: Fri Jan 18 12:20:47 GMT 2019
;; MSG SIZE  rcvd: 61

Remember to reload bash with source ~/.bashrc

More info on dig command here:

EDIT (21/01/19): If dig command is not available on your system, you will have to install bind-tools.

I’ve used Linux-Mint (based on debian) for this guide which already had bind-tools, but I also use Manjaro (based on Arch) and CentOS, which didn’t have it, so I had to install it separately, via simple command:
Arch – sudo pacman -Syu bind-tools
CentOS – sudo yum install bind-utils

Bind-tools can also be installed Windows OS from here:

Share & contribute

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.