Wednesday, July 28, 2010

Code to display your pc ip in linux prompt

Usually i do ssh connections to 2 or more machines. While switching form one teminal to other i use ifconfig to find to which pc it connected or i use to set title for teminals manully. But I feel there should be something else i can do, thought of putting ip in prompt itslef.

i have add code mentioned below in /etc/bashrc to effect it for all users.

code
#------ display ip in prompt -----
#Generally eth0 interface is used
ip=`ifconfig eth0 2>/dev/null |grep "inet addr" | cut -d ':' -f2| cut -d ' ' -f1`
#echo "--$ip--"
if [ -z $ip ]
then
#If not eth0 check for eth1
ip=`ifconfig eth1 2>/dev/null |grep "inet addr" | cut -d ':' -f2| cut -d ' ' -f1`
#echo "--$ip--"
if [ -z $ip ]
then
# Both interfaces are not available
ip="localhost"
fi
fi
#`PS1="[\u@\$ip \W]\$"`
#export PS1="[\u@\$ip \W]\$"
user_id=`id -u`
if [ $user_id -eq "0" ]
then
#for root users
export PS1="[\u@\$ip \W]# "
else
#For normal users
export PS1="[\u@\$ip \W]\$ "
fi
#clear
#----- end ---