Last update: 15-Apr-2020
Author: R. Koucha
Host's name in the prompt of bash

When executing interactively, bash displays the primary prompt PS1 when it is ready to read a command. Bash allows the prompt string to be customized by inserting a number of backslash-escaped special characters. Among them, "\h" (substituted by the host's name up to the first dot) and "\H" (the complete host's name).

For example:

$ hostname
$ export PS1="\H$ "
Host's name updating

If we change the host's name, the prompt is supposed to change:

rachid-pc$ sudo hostname new-pc
rachid-pc$ hostname

As we can see in the previous screenshot, the prompt is not updated with the new host's name. The reason for that is due to the behaviour of bash which gets and stores the host's name once at startup and use the stored value upon each prompt displays. Here is the source code of the intialization in bash 5.0:

/* Do whatever is necessary to initialize the shell.
   Put new initializations in here. */
static void
shell_initialize ()
  char hostname[256];
  int should_be_restricted;

  /* Line buffer output for stderr and stdout. */
  if (shell_initialized == 0)
      sh_setlinebuf (stderr);
      sh_setlinebuf (stdout);

  /* Sort the array of shell builtins so that the binary search in
     find_shell_builtin () works correctly. */
  initialize_shell_builtins ();

  /* Initialize the trap signal handlers before installing our own
     signal handlers.  traps.c:restore_original_signals () is responsible
     for restoring the original default signal handlers.  That function
     is called when we make a new child. */
  initialize_traps ();
  initialize_signals (0);

  /* It's highly unlikely that this will change. */
  if (current_host_name == 0)
      /* Initialize current_host_name. */
      if (gethostname (hostname, 255) < 0)
	current_host_name = "??host??";
	current_host_name = savestring (hostname);

The designer justifies that behaviour by the fact that the host's name is not likely to change. This is true or it would better to say it was true because with the advent of the uts namespaces in Linux, the host's name is likely to change when switching from one namespace to another from the same shell.

About the author

The author is an engineer in computer sciences located in France. He can be contacted here.