31

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?

Eliah Kagan
  • 116,445
  • 54
  • 318
  • 493
eeecoder
  • 333
  • 1
  • 3
  • 6
  • 1
    This question is more suited to [su] or to [unix.se]. Try `temp_cpu=$(sensors)` (this will turn newlines to spaces, though). You can use `grep` to filter the specific info you need, too. – edwin Jul 22 '13 at 22:16
  • 1
    @edwin why is the question not so suitable for this place? – tshepang Jul 23 '13 at 09:36
  • @Tshepang, this question is not specific to Ubuntu, it's just about the *Unix-like* shell. Thus, [unix.se]. – edwin Jul 23 '13 at 15:53
  • 1
    Did the policy/general opinion change? I thought this site welcomed questions that are not necessarily specific to Ubuntu. – tshepang Jul 23 '13 at 16:55
  • 1
    @edwin The comments are old so you're likely aware of this, but *this is on-topic*, per [the help](https://askubuntu.com/help/on-topic), [Are non-Ubuntu-spefic questions allowed?](https://meta.askubuntu.com/q/14663), [Are “not only Ubuntu-specific” questions on-topic?](https://meta.askubuntu.com/q/14523), [How do we tell if a question belongs here, or rather at stackoverflow/superuser?](https://meta.askubuntu.com/q/47), [Are bash/shell scripting questions on topic?](https://meta.askubuntu.com/q/13807) ([related](https://stackoverflow.blog/2012/03/22/respect-the-community-your-own-and-others/)) – Eliah Kagan Oct 11 '17 at 23:07

2 Answers2

40

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
1

You can also store the value of command as follows:

variableName=`command`
$variableName

For example:

currentDirectory=`pwd`
$currentDirectory
Melebius
  • 11,121
  • 8
  • 50
  • 77
Akshay Chopra
  • 291
  • 2
  • 4
  • think code formatting on your example got lost. –  Jan 29 '20 at 12:22
  • This works but this type of substitution cannot be nested, so [the other option](https://askubuntu.com/a/323167/250300) is preferred. @bac0n I’ve fixed the formatting problem. – Melebius Jan 29 '20 at 13:22