How to make bash update its idea of hostname

4

My bash prompt shows my hostname. If I change my hostname with the hostname command, in /etc/hosts, /etc/hostname and $HOSTNAME, the prompt still uses the old name. Is it possible to update this without logging out?

Sam Brightman

Posted 2010-10-16T08:08:05.133

Reputation: 540

Answers

6

If you have \h or \H in your prompt setting, its expansion is initialized when the shell starts, so you'll have to restart bash (exec bash). If that bothers you too much, change your prompt setting to print $HOSTNAME.

Gilles 'SO- stop being evil'

Posted 2010-10-16T08:08:05.133

Reputation: 58 319

3

If you want your bash prompt to update dynamically as the hostname (as reported by the /bin/hostname command) is updated, you can do this:

[root@foo ~]# PS1='[\u@`/bin/hostname` \W]\$ '
[root@foo ~]# hostname
foo
[root@foo ~]# hostname bar
[root@bar ~]# hostname baz
[root@baz ~]#

It's wasteful (runs a subshell every time you hit return -- not horrible but inelegant,) so I would only use this where the situation requires it. I use it when working on a base VM template that is used to generate multiple target VM instances where metadata about the instance is indicated in the hostname. And even then the custom PS1 is only set temporarily, as part of the initial login session while the role VM instance is being deployed.

krow10

Posted 2010-10-16T08:08:05.133

Reputation: 31