How can I query the hardware UUID of a Mac programmatically from a command line?

The ioreg command can be used for this task.

ioreg -d2 -c IOPlatformExpertDevice | awk -F\" '/IOPlatformUUID/{print $(NF-1)}'

Similarly, you can get the same information in a Property List (plist/xml) format by including the -a option which is useful for implementations that work with XML better. One command line example would be to use xmllint --xpath

ioreg -ad2 -c IOPlatformExpertDevice | 
  xmllint --xpath '//key[.="IOPlatformUUID"]/following-sibling::*[1]/text()' -

I often see the system_profiler command used for this task, however, I have found the ioreg method to be slightly faster if performance is a concern.

time system_profiler SPHardwareDataType | awk '/UUID/ { print $NF }'

real    0m0.295s
user    0m0.110s
sys     0m0.074s


time ioreg -d2 -c IOPlatformExpertDevice | awk -F\" '/IOPlatformUUID/{print $(NF-1)}'

real    0m0.029s
user    0m0.005s
sys     0m0.004s