Using code snippets

All we mean by the term code snippets is a prepared code that we can read into our current script. This is especially easy with vim being able to read the contents of other text files during editing:

ESC
:r <path-and-filename>

For example, if we need to read the contents of a file called if located in $HOME/snippets, we will use the following key sequences in vim:

ESC
:r $HOME/snippets/if

The contents of this file are read into the current document below the current cursor position. In this way, we can make the code snippets as complex as we need and maintain the correct indentations to aide readability and consistency.

So, we will make it our duty to always create a snippets directory in our home directory:

$ mkdir -m 700 $HOME/snippets

It is not required to share the directory, so it is good practice to set the mode to 700 or private to the user when it is being created.

When creating snippets, it is your choice to use a pseudo-code or real examples. My preference is to use real examples that are edited to reflect the requirements of the recipient script. The contents of a simple if snippet will be as follows:

if [ -z $1 ] ; then
echo "Usage: $0 <name>"
exit 2
fi

This gives us the layout to create an if statement with a practical example. In this case, we check to see whether $1 is unset and send an error to the user before exiting the script. The key is in keeping the snippet short to limit the changes that need to be made but make it easily understood and expandable as required.