How to map IP addresses in bash prompt

ipv4_address
Image by Indeterminate licensed under Public Domain via Commons

I regularly log into different Linux machines on the cloud and find complicated to identify on which machine I am by looking at the bash prompt. In fact, in cloud environments the bash prompt tends to  show an ugly internal IP address which I can never memorize. Plus, I always fear to log into the production environment by mistake and run experimental commands intended to be executed in the development environment.

In order to overcome my fears, I put together few lines of bash code to be added at the beginning of ~/.bashrc:

# get public IP address
alias myip="curl -s http://whatismyip.akamai.com"

# display environment in bash prompt
case $(myip) in
    1.2.34.567 ) PS1="[\u@\h DEV \W]\$ "
        ;;
    1.2.34.568 ) PS1="[\u@\h STAGE \W]\$ "
        ;;
    1.2.34.569 ) PS1="[\u@\h LIVE \W]\$ "
        ;;
    * ) PS1="[\u@\h OTHER \W]\$ "
        ;;
esac

Line 2 retrieves the IP address from an external web service and map it to myip. Lines 5-14 modify the bash prompt (PS1) based on the value of myip and each IP address (e.g. 1.2.34.567) is mapped to a string appearing in the prompt (e.g. DEV).

Reference: http://unix.stackexchange.com/questions/22615/how-can-i-get-my-external-ip-address-in-bash

Leave a Reply

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