Show IP at CLI Prompt

The initial request was to show private server IP on CLI prompt and derived to apply on server with public IP.

The steps for server with private IP are:

  1. Use command hostname to get server’s private IP
  2. Put the command above in bashrc file, so it will refresh every time login
  3. Modify the layout of CLI prompt
  4. Done

The steps for server with public IP are:

  1. Get public IP from config.me with command curl
  2. Save the result above in env variable
  3. Put commands above in a shell script
  4. Put the shell script above in rc.local file so it will refresh on every reboot (you can put it on bashrc too)
  5. Modify the layout of CLI prompt
  6. Done

For server with private IP

Get server IP

hostname -I

sed

Modify bashrc file, save returned IP to variable ip

ip=`hostname -I | sed -e 's/[[:space:]]*$//'`

sed
sed

Modify layout of CLI prompt, please refer below
Set Or Change Hostname In CentOS7
Change Command Line Prompt Color In CentOS7

Completed view of bashrc file

PS1='\[\e[01;36m\]\u\[\e[01;37m\]@\[\e[01;33m\]\H\[\e[01;37m\]-\[\e[01;35m\]'"$ip"'\[\e[01;37m\]:\[\e[01;32m\]\w\[\e[01;37m\]\$\[\033[0;37m\] '

sed

Re-login to confirm the result. Before and after
sed

For server with public IP

Get server public IP

curl -s ifconfig.me

sed

Create variable in environment for future replacement

echo "ip=1.2.3.4" >> /etc/environment  

sed

Save public IP to env variable and save as shell script

ip=$(curl -s ifconfig.me)
sed -i -e "s/ip=.*/ip=$ip/g" /etc/environment

sed

Add getit.sh to rc.local file to execute on every reboot

echo "/bin/bash /root/getip.sh" >> /etc/rc.d/rc.local

sed

Make files executable

chmod +x /etc/rc.d/rc.local /root/getip.sh

sed

Modify bashrc

PS1='\[\e[01;36m\]\u\[\e[01;37m\]@\[\e[01;33m\]\H\[\e[01;37m\]-\[\e[01;35m\]'"$ip"'\[\e[01;37m\]:\[\e[01;32m\]\w\[\e[01;37m\]\$\[\033[0;37m\] '

sed

Reboot server to confirm result
sed