How to set HOSTNAME in zsh?

zsh prompt expansion lets you do that prompt without having to do any calculation:

PS1='%$COLUMNS>╡>%F{cyan}╔╡%F{red}[%n]%F{cyan}:%F{yellow}[%m]%F{cyan}➾%F{green}[%~]%F{default}$PS1_GIT%F{cyan}${(l:COLUMNS::═:):-}%<<
╚═╡%F{default}'

Explained:

  • %$COLUMNS>╡>: right-truncate to $COLUMNS (a variable set dynamically by zsh to the width of the terminal) the part up to the next %<<.
  • %F{color}: set the foreground colour
  • %n, %m, %~: user name, machine name (hostname up to the first dot), current directory with ~-named-dirs.
  • ${(l:COLUMNS::═:):-}: left-pad the empty string (${:-}) to $COLUMNS length with characters.

%m is like ${HOST%%.*}. If you want the full host name ($HOST), use %M instead.


You should just set

HOSTNAME=$(hostname)

in your ~/.zshrc

Or as Caleb pointed out there is a variable HOST set, so to keep your prompt portable you could also do:

HOSTNAME=$HOST

You're using the wrong variable name. The $HOSTNAME environment variable is often set by the host system's init routines, but not always. In the context of a ZSH profile you should use the environment variable $HOST which is explicitly set by the shell. From man zshall:

PARAMETERS SET BY THE SHELL
    […]
    HOST The current hostname.

Note in that list that $HOSTNAME is not something that ZSH attempts to set, it is only set or not on the whim of your system's init system.

Also note that $HOST is not something you should use in cross platform shell scripting if you are hoping for portability to other shells—in that case the hostname binary is likely your best bet—but in the context of a ZSH profile the shell's own variable is the most appropriate thing to use.