Sunday, May 02, 2010

Tidbit: lnk - A Script To Create Symbolic Links (For Idiots)

Is there something that is so simple and something that you use so often that you should know it off the top of your head? And yet you brain just refuses to register said info... The nemesis of my memory is the simple ln command. I cannot, for the life in me, remember for sure which argument comes first: the target or the link name. To save repeatedly checking the help documentation, I wrote a tiny script. I thought I'd share this little gem now that I've been working on many virtual machines and realize how much I depend on it.



Use of this script is very simple and straightforward. You provide it with two file/folder paths: one to the target and another to the symbolic link you wish to create. Therefore, one must exist (the target) and the other must not (the link name). It doesn't matter in which order you put them. The script checks if they exist and creates a symbolic link from the link name to the target. That's about it!



Just copy the following code, save to an executable file and drop it in a folder included in your $PATH directories. Mine is $HOME/.bin/lnk. Enjoy!




#!/bin/bash

################################################################
# AUTHOR: SHANE JOE LAZAR
# SCRIPT NAME: lnk
# VERSION: 0.1
# LICENSE: GPLv2 or later
#
# CHANGELOG
# ---------
##0.1 (2010-03-26 15:37)
# - Initial release.
################################################################

#--VARIABLES--
ARG1="$1"
ARG2="$2"
TARGET=""
LINK=""
#-/VARIABLES--

# Catch unbound variables
set -u

#--FUNCTIONS--

# Usage instructions
usage () {
echo "----------------------------------------------------------"
echo ""
echo "$0:"
echo " This script creates a symbolic link to a file/directory."
echo " It will automatically determine which of the two provided"
echo " arguments will be the target and which will be the link."
echo ""
echo " $0 [path1] [path2] "
echo ""
echo "----------------------------------------------------------"
}

# Check if arguments provided
sanityCheck () {
if [[ -z "$ARG1" || -z "$ARG2" ]]
then
usage
exit 1
fi
}

# Function to create link
createLink () {
ln -s $TARGET $LINK
ls -l -a $LINK
}

# Function to check if files exist
checkArg () {
if [[ -e "$1" || -h "$1" ]]
then
echo "true"
else
echo "false"
fi
}

# Function to determine target and link
findArgs () {
CHECK1=`checkArg $ARG1`
CHECK2=`checkArg $ARG2`

# If both arguments exist
if [[ "$CHECK1" == "true" && "$CHECK2" == "true" ]]
then
echo ""
echo "Error: Both $ARG1 and $ARG2 exist."
echo " Cannot create link."
echo ""
usage
exit 1
# If argument 1 exists
elif [[ "$CHECK1" == "true" && "$CHECK2" == "false" ]]
then
TARGET=$ARG1
LINK=$ARG2
# if argument 2 exists
elif [[ "$CHECK1" == "false" && "$CHECK2" == "true" ]]
then
TARGET=$ARG2
LINK=$ARG1
fi
}

#-/FUNCTIONS--

#--RUN--
# Exit on errors
set -e

# Action!
sanityCheck
findArgs
createLink
exit 0
#-/RUN--

No comments: