Thursday, August 26, 2010

Including IP address of your pc in linux prompt

When working remote machine using teminals it some times make quite confusing which teminal is connected to which machine. One way is setting tittle to teminal makes confortable but we can make linux prompt to display IP dynamic by adding code in /etc/bashrc.

Code :-

#------ display ip in prompt -----
#Generally eth0 interface is used
ip=`ifconfig eth0 2>/dev/nul |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/nul |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



-------------------------
Add above code in /etc/bashrc. Open new terminal to see the change.

In above i have useded eth0 and eth1 interfaces only because most PCs uses it. we can chane it to ath0 or ath1 or wlan0 depending on ur requirement.