macOS hostname config

macOS has no /etc/hostname, instead you have to use scutil (“Manage system configuration parameters”) to (permanently) change your hostname. There are three “preferences” settable via scutil (using descriptions from the man page):

  • ComputerName: The user-friendly name for the system.
  • LocalHostName: The local (Bonjour) host name.
  • HostName: The name associated with hostname(1) and gethostname(3).

ComputerName isn’t super interesting; I’m not sure where it comes up. It’s got whitespace and special characters, and by default looks something like Steve’s MacBook Air.

LocalHostName is how the machine advertises itself on the local network. This must be a DNS-friendly name (no spaces) and cannot contain dots. Supposing you use something like best-mac, you can ping best-mac.local from other devices on the same LAN.

HostName is what the machine calls itself via the hostname command or the gethostname standard POSIX function. This is handy for a couple of my purposes:

  • Bash replaces \h in PS1 (a.o.) with the first component of the dotted hostname.
  • The self-reported “host” when using Telegraf (or similar).

Get

To show the current settings for each of these:

echo ComputerName LocalHostName HostName | xargs -n1 -t scutil --get

Set

To set LocalHostName:

sudo scutil --set LocalHostName best-mac

(There should be no output; if you try to use a dot it’ll complain SCPreferencesSetLocalHostName() failed: Invalid argument.)

This takes effect immediately. One place you can check the result is in the “Sharing” pane in “System Preferences”, which should display the setting at the top like:

Computers on your local network can access your computer at:

best-mac.local

To set HostName:

sudo scutil --set HostName best-mac.myself.org

This also takes effect immediately; call hostname to check. Call hostname -s to print the name without “any domain information”, which is what Bash uses as the value for \h.