In this article, we will show you a simple way to configure a custom header for all newly created bash scripts in Vim editor. This means that every time you open a new .sh file using vi/vim editor, the custom header will be automatically added to the file.

How to Create Custom Bash Script Header Template File

First start by creating the template file called sh_header.temp, which contains your custom bash script header, possibly under ~/.vim/ directory under your home.

$ vi ~/.vim/sh_header.temp

Next add the following lines in it (feel free to set your own template file location and custom header) and save the file.

Custom Header Template for Scripts

#!/bin/bash ################################################################### #Script Name : #Description : #Args : #Author :Aaron Kili Kisinga #Email :[email protected] ###################################################################

The template above will automatically add the required “shebang” line: “#!/bin/bash” and your other custom headers. Note that in this example, you will manually add the script name, description and arguments when editing your script content.

Configure autocmd in Vimrc File

Now open your vim initialization file ~/.vimrc for editing and add the following line to it.

au bufnewfile *.sh 0r /home/aaronkilik/.vim/sh_header.temp

Where:

au – means autocmd

– means autocmd bufnewfile – event for opening a file that doesn’t exist for editing.

– event for opening a file that doesn’t exist for editing. *.sh – consider all files with .sh extension.

So the above line instructs vi/vim editor to read the contents of the template file (/home/aaronkilik/.vim/sh_header.temp) and insert it into every new .sh file opened by a user.

Test Custom Bash Script Header in New Script File

Now you can test if all is working by opening a new .sh file using vi/vim editor, and your custom header should be auto-added there.

$ vi test.sh

For more information, see the Vim autocmd documentation.

Lastly, here are some useful guides concerning bash scripting and vim editor:

That’s all! If you have any questions or useful bash scripting tips and tricks to share, use the comment form below.