Monday, April 25, 2011

Versatility in the Linux CLI

With Linux there are two important assumptions with regard to the command line. First is to never conclude that you know everything.
Secondly, never assume that what you want to do can't be done.
Today I wanted to include two small parts from the output from the "sensors" command in Ubuntu 11.04 on my EeePC 901.
The whole output was as follows:

Adapter: Virtual device
temp1: +53.0°C (crit = +90.0°C)

Adapter: ISA adapter
Core 0: +1.0°C (crit = +90.0°C)

Adapter: ISA adapter
fan1: 1130 RPM

I wanted to include the value of temp1 (CPU temperature) and the fan1 speed in my Conky output in ubuntu.
I had previously used the -d and -f switches to choose the parts of the file delimited by something or other and then select a particular column (or field) in those parts selected by the delimiter switch (-d).
But, on the previous occasion, the two parts of the file I wanted were both delimited by "+", so it was easy to devise a command to choose just what I wanted and no more.
The command I used was
Core Temps: $alignr ${execi 6 /usr/bin/sensors | grep [+] | cut -d"+" -f2 | cut -d"(" -f1}

Here, "grep" picks just the lines with "+" in them, then "cut -d"+" -f2" divides the line in two fields before and after the "+" sign while -f2 picks the second field which is, in the above output, "53.0°C (crit = +90.0°C)"
Next the "cut -d"(" -f1" divides "53.0°C (crit = +90.0°C)" into two fields before and after the "(". Finally, -f1 picks just the first field which is "53.0°C"
This time, however, I want part of the third line, as above, but also the eleventh line (spaces count as lines) without any "+" in it.
Well, and here's the versatility, Linux has a neat way to select any line you want by use of the "head" and "tail" switches.
"head -n" selects the first "n" lines of a files while "tail -m" selects the last "m" lines of a file.
Therefore, to select the third line, you need to use this
head -3 | tail -1

The command I used to select the CPU temperature from the "sensors" output was:
CPU Temp: $alignr ${execi 6 /usr/bin/sensors |head -3 | tail -1 | cut -d"+" -f2 | cut -d"(" -f1}

Then to get the fan speed from the eleventh output line, I used
Fan Speed: $alignr ${execi 6 /usr/bin/sensors |head -11 | tail -1 | cut -d":" -f2}

No comments:

Post a Comment