Listing the number of CPUs in a system

Another really useful feature is that grep can count the matching lines and not display them. We can use this to count the number of CPUs or CPU cores we have on a system. Each core or CPU is listed with a name in the /proc/cpuinfo file. We can then search for the text name and count the output; the -c option used is shown in the following example:

$ grep -c name /proc/cpuinfo 

My CPU has four cores, as shown in the following output:

If we use the same code on another PC Model B that has a single core, we will see the following output:

We can again make use of this in a script to verify that enough cores are available before running a CPU-intensive task. To test this from the command line, we can use the following code, which we execute on a PC with just a single core:

$ bash
$ CPU_CORES=$(grep -c name /proc/cpuinfo)
$ if (( CPU_CORES < 4 )) ; then
> echo "A minimum of 4 cores are required"
> exit 1
> fi  

We only run bash at the start to ensure that we are not logged out of the system with the exit command. If this was in a script, this would not be required, as we would exit the script and not our shell session.

By running this on the Model B that has a single core, we can see the results of the script and also the indication that we do not have the required number of cores:

If you had a requirement to run this check in more than one script, then you could create a function in a shared script and source the script holding the shared functions within the script that needs to be checked:

function check_cores { 
 [ -z $1 ] && REQ_CORES=2 
CPU_CORES=$(grep -c name /proc/cpuinfo) 
if (( CPU_CORES < REQ_CORES  )) ; then 
echo "A minimum of $REQ_CORES cores are required" 
exit 1 
fi 
} 

If a parameter is passed to the function, then it is used as the required number of cores; otherwise, we set the value to 2 as the default. If we define this as a function in the shell on the Model B PC and display the details with the type command, we should see this as shown in the following screenshot:

If we run this on a single-core system and specify the requirement of just a single core, we will see that there is no output when we meet the requirement. If we do not specify the requirement, then it will default to 2 cores and we will fail to meet the requirement and we will exit the shell.

We can see the output of the function when run with the argument of 1, and then without arguments, in the following screenshot:

We can see how useful even the basics of grep can be within the scripts and how we can use what we have learned to start creating usable modules to add to our scripts.