👨‍💻 I offer long and short-term Ruby/Rails consultation. Let's talk.

How to Space AliasesPhoto by Diana Deaver

If you’re like me, your aliases have no spaces in them. They are all single-worded like these:

alias gs="git status"
alias gd="git diff "

A few days ago I started learning Elixir and Phoenix and realised Phoenix has commands like iex -S mix and mix phx.server. Coming from Ruby on Rails, I guess I’m too used to rails c and rails s so I sought to figure out how to get multi-worded aliases.

Shell Functions as Aliases

If you think about it, your .bashrc and .zshrc files are just Bash scripts. I never thought of it this way, and until today I didn’t know that you can define functions in them to use as aliases.

For almost every purpose, shell functions are preferred over aliases.

With the new-found knowledge, this is how I set up alias equivalents of the more verbose iex -S mix and mix phx.server commands.

phx() {
  if [[ $@ == "c" || "console" ]]; then
    command iex -S mix
  elif [[ $@ == "s" || "server" ]]; then
    command mix phx.server
  fi
}

Aliases with Spaces

With this, you can just run phx c or phx console to load IEx preloaded with your Phoenix app. Or phx s and phx server to start your Phoenix server; with c, console, s, server being parameters to the phx() function.

PS: You can run source /path/to/.*rc to immediately use your commands without restarting your shell, where *rc would be your “run commands” file (.bashrc, .zshrc or whatever).

This is shorter and faster to type and remember.

Happy coding!

    Powered By ConvertKit
    Subscribe to get updates on cool stuff I build and for new posts -- or follow me on Twitter and join me on my journey on rediscovering Ruby, Elixir, JavaScript and the Web.