0

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

2 Answers2

1

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
Xen2050
  • 14,391
0

Here's how I'd do it:

phycores=$(awk '/cores/{print $ 4;exit}' /proc/cpuinfo)
Cestarian
  • 1,997