I want to use the number of cores in a script and I am not sure what is the best approach to extract the number itself.

For example, the below extracts the number of physical cores, however how should the actual number be extracted so that it can be used as an input elsewhere?

lscpu | grep "Core(s) per socket" 
Core(s) per socket:    4

I am aware of tail -c N, however I am worried about the fragility of this approach when working on machines with more cores.

What is the best approach to reliably get the number of physical cores and threads per core for use as input an parameter elsewhere?


We could use awk or sed or even grep with Perl regexes to pick just the number from that line, e.g.

$ lscpu | sed -n 's/^Core(s) per socket: *//p'

But do you want that number, the number of cores in one socket? What if you have more than one socket on the machine:

$ lscpu |grep -i socket
Core(s) per socket:    2
Socket(s):             2

We could use awk to get both numbers and multiply them:

$ lscpu | awk '/^Core.s. per socket:/ {cores=$NF} /^Socket.s.:/ {sockets=$NF} END {print cores * sockets}'

I'm not sure if these count hyperthreads or not, and if we want hyperthreads or not, but we could just get the number on the CPU(s) line:

lscpu | awk '/^CPU.s.:/ { print $NF; exit }'

Or use nproc to get the total number of CPUs on the system.

$ nproc --all
|improve this answer|||||
  • nproc unfotunately counts hyperthreads. I am after all the physical cores on the machine, even if it's a multisocket server – Greg Jun 26 '17 at 4:30
  • @Dave, ok then, added a simple awk to show sockets * cores/socket – ilkkachu Jun 26 '17 at 10:58

You can use getconf utility for this . This should work for you

|improve this answer|||||
  • (Maybe, fails on OpenBSD 6.0, but is more portable than the Linux nproc or lscpu commands.) – thrig Jun 25 '17 at 13:52
  • this also counts hyperthreads – reox Nov 15 '17 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.