| 1 | #!/bin/bash |
| 2 | |
| 3 | # ncpus - Print the number of (virtual) processors |
| 4 | # |
| 5 | # Copyright 2009 Chuan-kai Lin |
| 6 | # |
| 7 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | # you may not use this file except in compliance with the License. |
| 9 | # You may obtain a copy of the License at |
| 10 | # |
| 11 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | # |
| 13 | # Unless required by applicable law or agreed to in writing, software |
| 14 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | # See the License for the specific language governing permissions and |
| 17 | # limitations under the License. |
| 18 | |
| 19 | CPUS=`grep '^processor' /proc/cpuinfo | wc -l` |
| 20 | |
| 21 | function isnumber { |
| 22 | [ "$1" -eq "$1" ] 2> /dev/null |
| 23 | } |
| 24 | |
| 25 | function limit { |
| 26 | if [ "$1" -gt 0 ] |
| 27 | then echo "$1" |
| 28 | else echo 1 |
| 29 | fi |
| 30 | } |
| 31 | |
| 32 | function offset { |
| 33 | if isnumber "$1" |
| 34 | then limit "$[CPUS$1]" |
| 35 | else echo "$CPUS" |
| 36 | fi |
| 37 | } |
| 38 | |
| 39 | if [ -z "$1" ] |
| 40 | then echo "$CPUS" |
| 41 | elif [ "$1" != "${1##+}" ] |
| 42 | then offset "$1" |
| 43 | elif [ "$1" != "${1##-}" ] |
| 44 | then offset "$1" |
| 45 | elif isnumber "$1" |
| 46 | then limit "$1" |
| 47 | else echo "$CPUS" |
| 48 | fi |