3 January 2017

How to create alias that work across Unix machines

I love shortcuts and like to do thing quickly. When I have to switch between two *nix machines (Mac or my other Linux based machine), I like to use the same shortcuts (or aliases) regardless of where I am.

One way to a chieve this is to write the alias/script that determine the type of environment it is currently running on.

Why do I need this?

Whenever I plug in the USB external drive into either OSX or Ubuntu, the drive will be mounted in the following location depends on the OS I am on.

  • For OSX the drive will be mounted at /Volume/USB_VOLUME_NAME/
  • for Ubuntu it is at /media/$USER/USB_VOLUME_NAME

Solution

So I have the following aliases in my ~/.zshrc (or ~/.bashrc) that allow me to quickly navigate to the same directory using the same shortcut thus remove the need to remember the path for different OS.

# inside your ~/.zshrc or ~/.bashrc
platform=`uname`
if [[ $platform == 'Linux' ]]; then
  alias g-codes='cd /media/$USER/USB_LABEL/codes'
  # more aliases that work with Linux
elif [[ $platform == 'Darwin' ]]; then
  alias g-codes='cd /Volumes/USB_LABEL/codes'
  # more aliases that work with OSX
fi

If you want more specific setup for different distribution of Linux then you can be event more specific using something like uname -r e.g.

platform=`uname`
if [[ $platform == 'Linux' ]]; then
  ## do things specific to Linux platform in general
  # ...
  if [[ `uname -r` == *"arch"* ]]; then
    ## Do things specific to Arch Linux only
    # ...
  elif [[ `uname -a` == *Ubuntu* ]]; then 
  ## Do things specific to Ubuntu Linux
  # ...
  elif [[ `uname -a` == *fc2* ]]; then 
  ## Do things specific to Fedora Linux 
  # ...
  fi
elif [[ $platform == 'Darwin' ]]; then
  ## Do things specific to OSX 
  # ...
fi

Hopefully, this will speed up your workflow and make your day more productive.

Happy Hacking.

Tags: tips automation shellscript linux