16

I want to make an alias for randomly changing my mac address

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

but the command substitution part is already resolved when executing the profile.

alias chrandmac='sudo ifconfig en0 ether 83:3a:bf:fc:4e:29'

Any thoughts as to why this occurs?

1.61803
  • 1,241
  • The $(....) part is done when the alias is defined, not when it runs. Use a shell function. – vonbrand Mar 30 '13 at 22:54
  • @vonbrand it's done when it's defined because $() happens inside of double quotes. That can be avoided. – jordanm Mar 31 '13 at 00:58
  • @jordanm, I've been badly bitten by aliases with arguments that seemed to work (along the lines you state). Better avoid that, use aliases only with fixed text replacement. – vonbrand Mar 31 '13 at 01:03

1 Answers1

24

You want to use a function instead of an alias. It can be put in your startup file just like an alias:

chrandmac() {
    sudo ifconfig en0 ether $(openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/.$//')
}

In order to get it to work with an alias, you need to use single quotes to prevent the expansion of the command substitution.

alias chrandmac='sudo ifconfig en0 ether $(openssl rand -hex 6 | sed '\''s/\(..\)/\1:/g; s/.$//'\'')'
jordanm
  • 42,678