Skip to main content
Bash Scripting

Create Code Snippets

By July 14, 2016September 12th, 2022No Comments

Create Code Snippets using the VIM Editor

Let’s take a look at how we can create code snippets and key mapping in the VIM editor to make our life a lot easier. Having already viewed the BASH scripting lesson 1  we will know to place the shebang at the start of our scripts. Wouldn’t it be nice is we could do that with a simple keystroke or two. We will see how easily we can create snippets of code that we can read into new shell scripts as we create them. This way we have a ready reference and a consistent approach for our coding. Vim is a brilliant editor that can read files in:

:r~/snippets/if

With that done and in place we can look at mapping keys within vi to certain actions. Vi can not just read files, but also, the our output of commands:

:r!date

Will run the date command and insert a line with the date on it into the file. Of course though, it is just the full date; using date +%x we can display just the date but vi will struggle with the %, so in vi we would escape that character:

:r!date "+%x"

Now of course we do not want to type all this in and have to get it correct every time, it would be easier to just type the date. So we can map this to a key. We can do this from within vi 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 

First we map the F2 key then enter the insert mode and add our hash bang. The F3 key is then mapped to add a new line below and type some commented text, enter command mode and run the date command. Then join the two lines together. Pure magic and easily shows how powerful vi is to your bash scripts.


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

shellscripting