Need help parsing string in bash
I have a script that uses sensors to get CPU temps in Ubuntu.
IN="`/usr/bin/sensors -f | grep 'Core ' | cut -f2 -d"+" | cut -f1 -d '.'`"
echo $IN
It yields results like this
96 100 98 102
What I need to do is be able to call it like cpu1 to get the first, cpu2 to get the second, and so on. I need to split it up so i can monitor core temps using MRTG, there might be a better wa开发者_开发技巧y, but I havent found one yet.
You can convert $IN
to an array like this:
TEMPERATURES=($IN)
Then you can index into that array to get a particular temperature; for example:
echo ${TEMPERATURES[0]}
If you pass a command-line parameter to your script, you can use that as an array index:
WHICH=$1 # 1st command line arg; $0 is name of script
TEMPERATURES=($IN)
echo ${TEMPERATURES[$WHICH]}
Calls to the script might then look like this (assuming the script is called cpu
):
$ ./cpu 0
96
$ ./cpu 1
100
$ ./cpu 2
98
$ ./cpu 3
102
IN="96 100 98 102"
I=0
for val in $IN; do
I=$((I+1))
eval "cpu$I=$val"
done
echo $cpu1
I answered literally how to get $cpu1 etc, but I suggest you do what @Richard suggests and use arrays :)
Instead of using lots of pipes to extract the cpu temp, you can do it in one single piping with awk:
#!/bin/sh
/usr/bin/sensors -f | awk -F"[+.]" -v c="^Core $1" '$0~c{print $2}'
Usage:
$./cpu 0
$./cpu 1
$./cpu 2
精彩评论