2

I have a bash script which asks a user for the number of CPU cores and saves it to variable named $cores. Now I want to add this variable to .bashrc, so I ask user how many CPU cores he has and then if he wants to save this value to .bashrc.

Now the question: how can I check if $cores already exists in .bashrc so the script won't ask the user again?

Thomas Dickey
  • 76,765

3 Answers3

5

Instead of prompting the user for how many cores the system has, why not just ask the system? This is better because it doesn't involve writing to a user-owned file. See something like this, which uses 'getconf' to request NPROCESSORS_CONF variable. Or for other systems, the ideas presented here may be helpful - using sysctl or a grep over /proc/cpuinfo to find the number of cores.

godlygeek
  • 8,053
  • It basically needs number of "make -jX" to use. Usually CPU Core number is used, but somebody may use something else. – albru123 Jun 20 '14 at 12:29
  • 1
    See also info libc 'Processor Resources' on a GNU system for more details. Using NPROCESSORS_ONLN (the number of online processors), would be better than NPROCESSORS_CONF (the number of processors present). – Stéphane Chazelas Jun 20 '14 at 12:51
0

Try this:

'awk /\$core/ { print }'
ryekayo
  • 4,763
-2

you can check whether a variable is set in bash using:

if [[ -z "$cores" ]]
then
    echo "not set"
else
    echo "set"
fi

This will check whether $cores variable is set or not. that is if $cores is null it will display "not set" otherwise "set". As a matter of fact .bashrc is not sourced automatically for non-interactive shells, such as those started when you execute a shell script. So you would put . .bashrc near the beginning of your .bash_login file, to ensure that .bashrc is sourced for both login and non-login interactive shells.

  • 2
    That checks if the variable is empty. That condition is true for unset variables but also for variables that are set to the empty string. [[ -z "${cores+set}" ]] would be for checking specifically if the variable is unset (that also works for array or hash variables with bash or zsh, but not ksh93 (though with bash if an array or hash is set but has no member, it's considered unset (a WA is to use declare -p array > /dev/null 2>&1))). – Stéphane Chazelas Jun 20 '14 at 12:41