Set Mac Device Name
Bash script for setting Mac device name and host name using the current logged in user. Can be deployed as part of post MDM enrolment process for Mac. Pair with an immediate inventory update to have accurate device names in Jamf/MDM.
#!/bin/bash
#
# Set Mac computer name and host name
logged_in_user=$(ls -l /dev/console | awk '{ print $3 }')
# Alt: logged_in_user=$(stat -f%Su /dev/console)
user_full_name=$(dscl . -read /Users/$logged_in_user RealName | cut -d: -f2 | sed -e 's/^[ \t]*//' | grep -v "^$")
user_full_name_host=(${user_full_name// /-})
# Get the system information
system_info=$(system_profiler SPHardwareDataType)
# Extract the model name from the output
model_name=$(echo "$system_info" | grep -i "Model Name" | awk '{print $3,$4}')
# Define Mac models
if [[ "$model_name" == "MacBook Air" ]]; then
host_suffix='MBA'
elif [[ "$model_name" == "MacBook Pro" ]]; then
host_suffix='MBP'
elif [[ "$model_name" == "Mac Mini" ]]; then
host_suffix='Mac Mini'
elif [[ "$model_name" == "iMac" ]]; then
host_suffix='iMac'
else
exit
fi
# Format computer name and host name
computer_name="$user_full_name's $host_suffix"
host_name="${user_full_nameHost}s-$host_suffix"
# Set the ComputerName and LocalHostName using scutil
/usr/sbin/scutil --set ComputerName "$computer_name"
/usr/sbin/scutil --set LocalHostName "$host_name"
exit 0