Skip to content

Instantly share code, notes, and snippets.

@Aldaviva
Last active October 25, 2016 01:09
Show Gist options
  • Save Aldaviva/7a04b01fca5a04841f459374e9e47c6f to your computer and use it in GitHub Desktop.
Save Aldaviva/7a04b01fca5a04841f459374e9e47c6f to your computer and use it in GitHub Desktop.
Make symbolic linking easier.

smart-ln.sh

This is an alias script for ln -s that takes arguments in either order and creates your symlink based on which files exist.

Who can ever remember the order of arguments to ln -s? It doesn't even matter because the user's intention is always unambiguous. Also the argument order is reversed in junction.exe on Windows, which makes it even harder to remember if you use both.

For example, GNU ln works fine with ln -s /tmp mytmp, but if you forget the argument order, can't figure out the useless manpage, and use the wrong order ln -s mytmp /tmp, then it not only won't return an error, it will make a broken symlink called /tmp/mytmp that points to the nonexistent mytmp. This is stupid. It's clear that the user wants a symlink called mytmp that points to /tmp, because /tmp exists and mytmp doesn't.

Installation

$ sudo curl -o /usr/local/bin/smart-ln.sh https://gist.githubusercontent.com/Aldaviva/7a04b01fca5a04841f459374e9e47c6f/raw/c6386f8bb1620867f1aad1d7623c0e8426f5a93b/smart-ln.sh
$ sudo chmod +x /usr/local/bin/smart-ln.sh
$ echo -e "\nalias ln='/usr/local/bin/smart-ln.sh'" >> ~/.bash_aliases
$ source ~/.bash_aliases

If your operating system doesn't use .bash_aliases, you can try using ~/.bashrc instead.

Usage

$ ln -s /tmp mytmp
$ ln -s mytmp /tmp

The order of the two path arguments doesn't matter. Both will work.

Limitations

This script only fixes ln -s and no other forms of ln due to laziness and the fact that symlinks are the only reason to ever use ln. If you try to call this script with --interactive, --physical, --verbose, or any other arguments that aren't -s or --symbolic, it will delegate to /bin/ln.

#!/bin/bash
# https://gist.github.com/Aldaviva/7a04b01fca5a04841f459374e9e47c6f
# Usage: ln -s mytmp /tmp
# You can alias ln to this script in your shell configuration.
if [ "$1" == "-s" ] || [ "$1" == "--symbolic" ]; then
if [ -e "$2" -a ! -e "$3" ]; then
/bin/ln -s "$2" "$3";
elif [ ! -e "$2" -a -e "$3" ]; then
/bin/ln -s "$3" "$2";
elif [ -e "$2" -a -e "$3" ]; then
>&2 echo "Error: $2 and $3 both exist";
exit 1;
else
>&2 echo "Error: neither $2 nor $3 exist";
exit 1;
fi
else
/bin/ln "$@";
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment