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,201
  • 2
  • 15
  • 23
  • 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

25

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
  • 41,988
  • 9
  • 116
  • 113