Skip to main content
Bash Scripting

Creating Code Snippets to use in VIM and Mapping Keys to Actions

By April 12, 2013October 3rd, 2016No Comments

code snippets

Code Snippets

Having looked at lesson 1 at the very basics of creating bash shell scripts we want to ensure that we code correctly. Creating code snippets that we can read into new shell scripts is a great way of providing standardization and reference. A code snippet is nothing more than us pre-creating sample code and reading that code backing to VIM when we need it.

Consider creating a subfolder in your home directory called snippets. In here just create a collection of files with names based on the type of code example they contain, such as if, while etc.

To read and existing file into the current document when using vim we can use the following code from the command menu:

:r ~/snippets/if

Running Commands in VIM

With our code snippets in place, we can look at other shortcuts that we may want to make use of such as using commands or key maps in vim. As well as reading in files to vim we can read the output from commands; just add the exclamation mark in from the command. For example to read the data and time into the current document we can use the following command:

:r!date

This does add the date but, of course,  it is just the full date; using date +%x we can display just the date. As vim will struggle with the %, we escape that character and write as in the following:

:r!date “+\%x”

Key Mapping

Now, of course, we do not want to type all this in  every time we need the date. It would be easier to just type the date without worrying about the VIM syntax. Thankfully the developers at VIM has thought of this for us and allow us tp map a key to this macro. We can do this from within vim but really we would make this permanent but adding something like this to our ~/.vimrc file:

map <F2> i#!/bin/bash <ESC>
map <F3> o#This file was created on <ESC>:r!date "+\%x"<ESC>kJ 

Firstly we map the F2 key entering the insert mode and adding our shebang. Then the F3 key is then mapped to add a new line below and type some commented text. This comes before entering the command mode and running the date command. The date command appears on a new line so we have to be a little clever in the macro joining the two lines together. The letter k takes us up one line and J joins the current line with the line below. This is pure magic and easily shows how powerful vim is to your bash scripts and can become your IDE.


My Book on Shell Scripting is available from all good book shops and the publisher Packt

Mastering Linux Shell Scripting by Andrew Mallett.jpg