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)}'