Bash script, get number of physical cores as number and iterate

I wrote a script that shows a number of physical cores of the machine. However, I would like the result to be a number, not a string.

Here's the script:

phycores=echo $sudoPW | cat /proc/cpuinfo | grep -m 1 "cpu cores" | awk '{print $ 4;}'
echo $phycores
for i in {1..$phycores}
do echo "Core $i"
done
5

1 Answer

I'm spotting a few issues:

  • Why the echo $sudoPW piped to cat? cat ignores it without a - somewhere.

  • And $phycores doesn't get set without backticks or $() that can't be the actual script you're running, and it still sets $phycores to a number with a newline?

  • The {1..n} construct doesn't work with a variable, if your $phycores were 4 then it just sets the $i variable to {1..4}. See this Q on stackoverflow for more details. (A newline in $phycores shouldn't matter)

Anyway, this should be a more working script

phycores=$(echo $sudoPW|cat - /proc/cpuinfo|grep -m 1 "cpu cores"|awk '{print $ 4;}')
echo $phycores
for ((i=1;i<=phycores;++i))
do echo "Core $i"
done
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like