Mac – How to auto paste above return value on command line

command linemac addressscript

I am trying to create a very simple script (.command) that
will basically change my mac address.. i do know that the command: openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//' will return me a random hex digits, now I want that when it will run this line sudo ifconfig en0 ether ## the hash tag will replace the random hex digits that it returned above.

thank you,
mendel

Best Answer

I'm sure this isn't exactly the most elegant way to do this but the following will work:

MAC="$( openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//' )" && sudo ifconfig en0 ether $MAC

The above is how you could do that in a single command. It makes use of bash's variables. The first part assigns the vairable MAC to the output of your randomisation command then the second part inserts this output where you desire by referencing $MAC. If you're looking to integrate it into a bash script, you can modify it slightly like below; which does exactly the same thing just on multiple lines:

#! /bin/bash

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

sudo ifconfig en0 ether $MAC

Hope that helps!

Kind regards, Tom