将变量设置为终端命令的结果 (Bash)
Set variable to result of terminal command (Bash)
所以我正在尝试制作一个 bash 文件,每 10 分钟轮换一次我的 MAC 地址,每次都分配一个随机的十六进制数。我想将一个名为 random_hexa
的变量分配给此命令的结果:openssl rand -hex 6 | sed 's/\(..\)/:/g; s/.$//'
。然后我会获取变量并稍后在脚本中使用它。
知道如何获取 openssl
命令的结果并将其分配给变量供以后使用吗?
谢谢!
你想要"command substitution"。传统的语法是
my_new_mac=`openssl rand -hex 6 | sed 's/\(..\)/:/g; s/.$//'`
Bash也支持这种语法:
my_new_mac=$(openssl rand -hex 6 | sed 's/\(..\)/:/g; s/.$//')
您可以使用 $()
语法存储任何命令的结果,例如
random_hexa=$(openssl...)
像这样存储变量:
myVar=$(openssl rand -hex 6 | sed 's/\(..\)/:/g; s/.$//')
现在$myVar
可以用来指代你的号码:
echo $myVar
$()
在 subshell, which is then stored in the variable myVar
. This is called command substitution.
中运行括号内的命令
所以我正在尝试制作一个 bash 文件,每 10 分钟轮换一次我的 MAC 地址,每次都分配一个随机的十六进制数。我想将一个名为 random_hexa
的变量分配给此命令的结果:openssl rand -hex 6 | sed 's/\(..\)/:/g; s/.$//'
。然后我会获取变量并稍后在脚本中使用它。
知道如何获取 openssl
命令的结果并将其分配给变量供以后使用吗?
谢谢!
你想要"command substitution"。传统的语法是
my_new_mac=`openssl rand -hex 6 | sed 's/\(..\)/:/g; s/.$//'`
Bash也支持这种语法:
my_new_mac=$(openssl rand -hex 6 | sed 's/\(..\)/:/g; s/.$//')
您可以使用 $()
语法存储任何命令的结果,例如
random_hexa=$(openssl...)
像这样存储变量:
myVar=$(openssl rand -hex 6 | sed 's/\(..\)/:/g; s/.$//')
现在$myVar
可以用来指代你的号码:
echo $myVar
$()
在 subshell, which is then stored in the variable myVar
. This is called command substitution.