Apple - How can I find the serial number on a mac programmatically from the terminal?
The system_profiler command provides a direct answer that’s easily human readable (assuming you are on 10.3 or newer), but you can also use ioreg for the task as it generally completes faster.
system_profiler SPHardwareDataType
is the data type that contains the core hardware information, and you can use grep or awk to pare things down further as needed:
system_profiler SPHardwareDataType | awk '/Serial/ {print $4}'
or
ioreg -l | awk '/IOPlatformSerialNumber/ { print $4;}'
Both of those commands take between 0.5 and 0.2 seconds to run on modern SSD Macs, so if you want to optimize the command and remove the " you can have your answer in 0.005s or so:
ioreg -c IOPlatformExpertDevice -d 2 | awk -F\" '/IOPlatformSerialNumber/{print $(NF-1)}'
This also works…
ioreg -l | grep IOPlatformSerialNumber
C++ example:
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
std::string
getSerialNumber()
{
CFStringRef serial;
char buffer[32] = {0};
std::string seriaNumber;
io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,
IOServiceMatching("IOPlatformExpertDevice"));
if (platformExpert)
{
CFTypeRef serialNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert,
CFSTR(kIOPlatformSerialNumberKey),
kCFAllocatorDefault, 0);
if (serialNumberAsCFString) {
serial = (CFStringRef)serialNumberAsCFString;
}
if (CFStringGetCString(serial, buffer, 32, kCFStringEncodingUTF8)) {
seriaNumber = buffer;
}
IOObjectRelease(platformExpert);
}
return seriaNumber;
}