Useful scripts

Explore a collection of useful scripts, including a detailed bash script for modifying host names on macOS, accompanied by important usage notes and a disclaimer regarding their support.

2 min read
ℹ️
All the scripts below are provided on an as-is basis. Please check their output and effects before rolling them out. We are not available to support our customers on these scripts.
  1. macOS
    1. Modifying all host names

macOS

Modifying all host names

#!/bin/bash
# This script changes the hostname on macOS by updating:
# - ComputerName: The user-friendly name seen in Sharing preferences.
# - LocalHostName: The Bonjour name used on the local network (must be sanitized).
# - HostName: The system’s POSIX name.
# - NetBIOSName: Used for SMB file sharing.
#
# Usage: sudo ./change_hostname.sh NewHostname

# Check if the new hostname is provided
if [ "$#" -ne 1 ]; then
    echo "Usage: sudo $0 <new_hostname>"
    exit 1
fi

NEW_HOSTNAME="$1"

# Sanitize the new hostname for LocalHostName (Bonjour) requirements:
# - Convert to lowercase, remove invalid characters (keeping only letters, numbers, and hyphens).
SANITIZED_HOSTNAME=$(echo "$NEW_HOSTNAME" | tr '[:upper:]' '[:lower:]' | tr -cd '[:alnum:]-')

echo "Changing hostname to: $NEW_HOSTNAME"
echo "Using sanitized LocalHostName: $SANITIZED_HOSTNAME"

# Change the ComputerName (visible in Sharing settings)
sudo scutil --set ComputerName "$NEW_HOSTNAME"

# Change the LocalHostName (used for Bonjour)
sudo scutil --set LocalHostName "$SANITIZED_HOSTNAME"

# Change the HostName (the underlying POSIX hostname)
sudo scutil --set HostName "$NEW_HOSTNAME"

# Optionally, change the NetBIOS name for SMB file sharing
sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName -string "$NEW_HOSTNAME"

echo "Hostname successfully updated!"
echo "A reboot might be required for all changes to fully take effect."
Did this answer your question?