Set variable to result of terminal command (Bash)

我的未来我决定 提交于 2019-12-12 01:57:22

问题


So I am TRYING to make a bash file that rotates my MAC address every 10 minutes with a random hexadecimal number assigned each time. I would like to have a variable called random_hexa assigned to the result of this command: openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'. I would then take the variable and use it later on in the script.

Any Idea how to take the result of the openssl command and assign it to a variable for later use?

Thanks!


回答1:


Store the variable like so:

myVar=$(openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//')  

Now $myVar can be used to refer to your number:

echo $myVar

$() runs the command inside the parenthesis in a subshell, which is then stored in the variable myVar. This is called command substitution.




回答2:


You want "command substitution". The traditional syntax is

my_new_mac=`openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//'`

Bash also supports this syntax:

my_new_mac=$(openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//')



回答3:


You can store the result of any command using the $() syntax like

random_hexa=$(openssl...)



来源:https://stackoverflow.com/questions/29663820/set-variable-to-result-of-terminal-command-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!