This is a copy of my post from stackoverflow; I realize I should have asked it here…
I want to run a script that changes the hostname and have my bash prompt (PS1 variable) update immediately with the proper hostname. How do I make this happen?
I run this
#!/bin/bash
# Usage: ./changehost <newhostname>
#Do two sed's to edit the files for persistent hostname change
sed -i s/$(hostname)/$1/g "/etc/hosts"
sed -i s/$(hostname)/$1/g "/etc/sysconfig/network"
#run the hostname command with new hostname to update it
hostname $1
In a terminal like so and get this
[user@host dir]# ./changehost newhostname
[user@host dir]#
But what I want is this
[user@host dir]# ./changehost newhostname
[user@newhostname dir]#
The terminal is updated properly only when I open up a new shell.
I have also tried to do
export PS1='somestring'; export PS1='[\u@\h \W]\$'
outside of the script in the terminal and it does switch to 'somestring' and back, but the hostname is unchanged. :\
Is it possible that the \h is stored in memory when the process begins and can't be changed after startup?
Best Answer
If your PS1 is similar to:
The value of \h is only set on bash startup. Therefore, if you change the hostname, you need to start a new bash instance:
Will replace bash by a new instance (with the value of \h updated). Sadly, it will exit a running script. Some other magic is needed to make the change for a shell script that follow executing code after the hostname change. I believe that it is not possible to keep the same script running with an updated hostname and
\h
. But I also believe that that is not what you are asking for.