如何将命令的输出分配给变量?


19

有没有一种方法可以给变量赋值,即通过编写任何命令在终端获得的值?

示例命令: sensors

由此我们得到CPU温度。如何将此值分配给temp_cpu变量?


1
这个问题更适合于超级用户Unix&Linux。尝试temp_cpu=$(sensors)(不过,这会将换行符转换为空格)。您也可以grep用来过滤所需的特定信息。
埃德温

1
@edwin为什么这个问题不太适合这个地方?
tshepang

@Tshepang,这个问题不是Ubuntu特有的,只是关于类Unix的 shell。因此,Unix和Linux
埃德温

1
政策/一般性意见是否改变?我以为该网站欢迎不一定特定于Ubuntu的问题。
tshepang

Answers:


27

是的,您使用 my_var=$(some_command)。例如:

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

或者对于您的特定示例,使用sedgrep获取所需的特定数据:

$ cpu_temp=$(sensors acpitz-virtual-0 | grep '^temp1:' | sed 's/^temp1: *//;s/ .*//')
$ echo $cpu_temp
+39.0°C
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.