How do I assign the output of a command to a variable?

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?


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
+39.0°C

You can also store the value of command as follows:

variableName=`command`
$variableName

For example:

currentDirectory=`pwd`
$currentDirectory