【问题标题】:Set variable to result of terminal command (Bash)将变量设置为终端命令的结果(Bash)
【发布时间】:2015-06-22 05:11:30
【问题描述】:
所以我正在尝试制作一个 bash 文件,该文件每 10 分钟轮换一次我的 MAC 地址,每次都分配一个随机的十六进制数字。我想将一个名为random_hexa 的变量分配给此命令的结果:openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'。然后我会获取变量并稍后在脚本中使用它。
知道如何获取openssl 命令的结果并将其分配给变量以供以后使用吗?
谢谢!
【问题讨论】:
标签:
bash
openssl
mac-address
【解决方案1】:
像这样存储变量:
myVar=$(openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//')
现在$myVar可以用来指代你的号码了:
echo $myVar
$() 在subshell 中运行括号内的命令,然后将其存储在变量myVar 中。这称为 command substitution。
【解决方案2】:
您想要“命令替换”。传统语法是
my_new_mac=`openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'`
Bash 也支持这种语法:
my_new_mac=$(openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//')
【解决方案3】:
您可以使用$() 语法来存储任何命令的结果,例如
random_hexa=$(openssl...)