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?

  • 2
    Note that the .bashrc belongs to the user and may be shared by different machines. Jun 20, 2014 at 12:54

3 Answers 3


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.

  • It basically needs number of "make -jX" to use. Usually CPU Core number is used, but somebody may use something else.
    – albru123
    Jun 20, 2014 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). Jun 20, 2014 at 12:51

Try this:

'awk /\$core/ { print }'
  • The {print} is redundant in this case (it is awk's default)...
    – jasonwryan
    Jun 21, 2014 at 1:40

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

if [[ -z "$cores" ]]
    echo "not set"
    echo "set"

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))). Jun 20, 2014 at 12:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .