Portable way to find the number of processors/CPU's in a shell script?

Viewed 2335

Since it's common to write shell scripts which pass the number of jobs to a command, I'm interested to know what a good, portable way is to get the number of processors on mainstream * Unix systems.

Something like this but not depending on Python.


* By mainstream, I mean that will work on popular Unix system used in production today (Linux/BSD's/Darwin? But the more portable the better).

3 Answers

I'll throw in my one-liner heavily influenced by ideasman42's answer above:

nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null
Related