This post will show how to set the hostname of a mac on the terminal, we will use the tool scutil and dscacheutil to flush the DNS cache.

Provide the sudo password when you are asked for.

Hostname

Hostname is the fully qualified hostname, including the domain, e.g. myMac.tld.com

LocalHostname

LocalHostname is the name of the mac in the local network, e.g. myMac.lan. When needed add the trailing .local or .lan or just omit the extension.

ComputerName

ComputerName is the user-friendly or speaking name of the mac, e.g. myMac, it will be used e.g. in Finder.

Perform the following tasks

Commands with pseudo-code:

sudo scutil --set HostName <NewNameOfMac>
sudo scutil --set LocalHostName <NewNameOfMac>
sudo scutil --set ComputerName <NewNameOfMac>
dscacheutil -flushcache

Use values as Example, the new name will be mac123:

sudo scutil --set HostName mac123.tld.com
sudo scutil --set LocalHostName mac123.local
sudo scutil --set ComputerName mac123
dscacheutil -flushcache