Quantcast
Channel: Function to get specified key from /proc/cpuinfo - Code Review Stack Exchange
Viewing all articles
Browse latest Browse all 2

Answer by Mat for Function to get specified key from /proc/cpuinfo

$
0
0

Useless use of cat

Grep can open files all by itself, cat isn't necessary in most circumstances. Also, quote everything - that's save you some debugging when you need to handle spaces in them - like for the "model name" property.

target_line=$(grep -m1 ^"$1" /proc/cpuinfo)

-m1 to stop at the first match, so you won't get weird results when you run your script on a machine with more CPUs. That's not portable unfortunately (not in POSIX), so if you don't have that, the usual options are: pipe to head -n 1, use awk instead and exit early, sed and exit early. The latter two can do it all in one go too.

Use your shells string manipulations for simple things

Assuming you want everything after the :, you can simply do:

value="${target_line##*: }"

See How do I do string manipulations in bash? for more like this, or the POSIX parameter expansion reference.

function keyword not necessary

It's less portable and doesn't buy you anything, so just omit it. See difference between “function foo() {}” and “foo() {}” for more details.

Variable names don't need to be in all caps

Personal preference of course, but especially for locals, lowercase is good - keep uppercase for globals/environment variables.

So:

get_cpuinfo_prop () {
  target_line=$(grep -m1 ^"$1" /proc/cpuinfo)
  echo "${target_line##*: }"
}

Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>