Ubuntu – How to assign the output of a command to a variable

command line

Is there a way to assign a value to a variable, that value which we get in terminal by writing any command?

Example command: sensors

From that we get CPU temperature. How can I assign this value to a temp_cpu variable?

Best Answer

Yes, you use my_var=$(some_command). For example:

$ foo=$(date)
$ echo $foo
Mon Jul 22 18:10:24 CLT 2013

Or for your specific example, using sed and grep to get at the specific data you want:

$ cpu_temp=$(sensors acpitz-virtual-0 | grep '^temp1:' | sed 's/^temp1: *//;s/ .*//')
$ echo $cpu_temp
Related Question