Posts Show IP at CLI Prompt
Post
Cancel

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

1
hostname -I

sed

Modify bashrc file, save returned IP to variable ip

1
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

1
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

1
curl -s ifconfig.me

sed

Create variable in environment for future replacement

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

sed

Save public IP to env variable and save as shell script

1
2
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

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

sed

Make files executable

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

sed

Modify bashrc

1
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

This post is licensed under CC BY 4.0 by the author.