Set LocalHostName using scutil - errors - problems with hidden and illegal characters

mcmulligan
New Contributor II

I know there are a number of other posts related to setting up your Macs with a script that does something like:

....
# newHostName="$smallImportantStr0-$smallImportantStr1-$smallImportantStr2"
# scutil --set ComputerName "$newHostName"
# scutil --set HostName "$newHostName"
# scutil --set LocalHostName "$newHostname" 

Only I encountered errors setting LocalHostName. Sure there is another way to do it (see the command systemsetup -setlocalsubnetname) but that doesn't fix the errors.

After quite a bit of checking the syntax and strings involved, I discovered that my $newHostName string had a new line buried in it and macOS was just not having it.

LocalHostName is fussy and there are a bunch of illegal characters that generate errors.

The errors didn't show up when I entered the command manually because I used copy and past to put in the string, which necessarily dropped the hidden [and illegal] characters.

 

This took me a while to figure out, so I thought I would leave this hint for you....

I was able to fix it by cleansing my string with the following command(s):

 

newName=$(echo "$smallImportantString0-$smallImportantString1-$smallImportantString2" |  tr '[a-z]' '[A-Z]')
NewHostName=${newName//[$'\t\r\n']} && NewHostName=${NewHostName%%*( )}

 

My clean up process is perhaps not elegant, but it worked...  Like almost everything in bash, there are many ways to accomplish a given job.  

 

Reference: 

https://stackoverflow.com/questions/19345872/how-to-remove-a-newline-from-a-string-in-bash

1 REPLY 1

cbrewer
Valued Contributor II

I've found on macOS 12 that you need a short pause in between scutil commands to set the names.

  scutil --set ComputerName "${computerName}"
  sleep 1
  scutil --set LocalHostName "${computerName}"
  sleep 1
  scutil --set HostName "${computerName}"
  sleep 1