How to quickly create fully functional shell scripts using VIM

  • Download the VIM template script
  • Install it (:source pathtovim_script)
  • Create the following script in .vim/templates/sh:
#!/bin/sh
 
VERSION="$0 v1.0"
 
usage()
{
cat << EOF
 
Usage: $0 [options]
 
OPTIONS:
  -b, --black-and-white         Suppress colored output.
  -h, --help                    Show this message.
  -V, --version                 Show Program version.
EOF
}
 
# don't forget to add ":" after an option if it needs args (they will be stored as $2, $3, etc. in the next while statement)
TEMP=`getopt -o bhV --long black-and-white,help,version \
     -n '$0' -- "$@"`
 
#echo $#
if [ $# -lt 1 ] ; then echo "Please type $0 --help for help" >&2 ; exit 1 ; fi
 
eval set -- "$TEMP"
 
while true ; do
        case "$1" in
                -b|--black-and-white) BLACKNWHITE=1; shift ;;
                -h|--help) usage ; shift ; exit 0 ;;
                -V|--version) echo $VERSION ; shift ; exit 0 ;;
                --) shift ; break ;;
                *) echo "Please type $0 --help for help" ; exit 1 ;;
        esac
done
 
if [ ! ${BLACKNWHITE} ]
then
RED="\033[1;31m"
GREEN="\033[1;32m"
YELLOW="\033[1;33m"
WHITE="\033[1;37m"
NONE="\033[0m"
fi
 
SAMPLEMESSAGE="${RED}HELLO WORLD${NONE}"
 
#
# "this is the end, my friend"
#
echo ""
exit 0
  • Add the following line in .vimrc:
  au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod a+x <afile> | endif | endif
  • That's it! next time you will edit a new .sh file, it will load the template and automagicaly made it executable :)