Why a symlink
Many times when working with hosting apps, there comes a time or a need to have certain code in more than one place at the same time. To accomplish this, a ‘symlink’ can be used. For example, a basic NGinx or Apache server will have a path to host files on like /var/www/my-site/
. It would not be recommended to have the code exist within that path directly though, as that would create a lot of complications when attempting to do simple updates or roll back code quickly. It’s much easier in this simple case to have /home/user/code/v1/
also be /var/www/my-site
so when v2
is created, it can now be /var/www/my-site
instead of v1
. Symlinks allow for this, and are the preferred mechanism.
Symlink definition
In computing, a symbolic link (also symlink or soft link) is a term for any file that contains a reference to another file or directory in the form of an absolute or relative path and that affects pathname resolution.
Wikipedia definition, 03-2018
In lamens terms, it’s an alias folder or file. In Windows logic, it’s like a shortcut (but not).
Creating a symlink
Depending on your OS, symlinks can be created with a command from Terminal or Command Prompt.
Here is a full script that can be used to create a symlink.
# Pulled from https://stackoverflow.com/questions/18641864/git-bash-shell-fails-to-create-symbolic-links | |
# https://stackoverflow.com/users/124119/camilo-martin | |
# Detect windows (assumes we are in 'msysgit' or similar). | |
windows() { [[ -n "$WINDIR" ]]; } | |
# Cross-platform symlink function. | |
# With one parameter, it will check whether the parameter is a symlink. | |
# With two parameters, it will create a symlink to a file or directory, | |
# with syntax: link $linkname $target | |
link() { | |
if [[ -z "$2" ]]; then | |
# Link-checking mode. | |
if windows; then | |
fsutil reparsepoint query "$1" > /dev/null | |
else | |
[[ -h "$1" ]] | |
fi | |
else | |
# Link-creation mode. | |
if windows; then | |
# Windows needs to be told if it's a directory or not. Infer that. | |
# Also: note that we convert `/` to `\`. In this case it's necessary. | |
if [[ -d "$2" ]]; then | |
cmd <<< "mklink /D \"$1\" \"${2//\//\\}\"" > /dev/null | |
else | |
cmd <<< "mklink \"$1\" \"${2//\//\\}\"" > /dev/null | |
fi | |
else | |
# You know what? I think ln's parameters are backwards. | |
ln -s "$2" "$1" | |
fi | |
fi | |
} |
Removing a symlink
In the same flow, to remove a symlink cross-platform, here is the script.
# Pulled from https://stackoverflow.com/questions/18641864/git-bash-shell-fails-to-create-symbolic-links | |
# https://stackoverflow.com/users/124119/camilo-martin | |
# Detect windows (assumes we are in 'msysgit' or similar). | |
windows() { [[ -n "$WINDIR" ]]; } | |
# Remove a link, cross-platform. | |
rmlink() { | |
if windows; then | |
# Again, Windows needs to be told if it's a file or directory. | |
if [[ -d "$1" ]]; then | |
rmdir "$1"; | |
else | |
rm "$1" | |
fi | |
else | |
rm "$1" | |
fi | |
} |