Making shell scripts executable via editor hooks

Posted by Steve on Thu 6 Dec 2007 at 11:42

If you spend a lot of time creating new shell scripts, be they plain shell or scripting languages such as perl or python, then it can be very useful to make new scripts be executable by default. Here we'll show two simple recipes for GNU Emacs and vim to do just that.

The basic aim is to run a hook whenever a file is written, which will "chmod 755 $file" if the file you're saving looks like a shell script. We do this by examining the first line of the file looking for a "shebang" line which looks something like this:

#!/bin/sh

If that line is present, or one similar to it, we can then change the permissions of the file.

GNU Emacs

Reece Hart wrote a lisp file, shebang.el which allows files to be made executable when they are saved if they contain a shebang line pointing to an executable which exists.

To use this download shebang.el, and place it in a directory upon your emacs load-path, and require it in your startup file

If the term load-path doesn't mean anything to you then create the directory ~/.emacs.d/ and download the file into it. Once you've done that add this to the end of your .emacs file (creating it if necesary):


;; Add ~/.emacs.d/ to the load-path if the directory exists
(if (file-exists-p (expand-file-name "~/.emacs.d"))
      (add-to-list 'load-path (expand-file-name "~/.emacs.d/")))

;; Load the shebang module
(require 'shebang)

vim

To get this effect in Vim add the following lines to the end of your ~/.vimrc file - creating it if necessary:

"
" automatically give executable permissions if file begins with #! and contains
" '/bin/' in the path
"
au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod a+x <afile> | endif | endif

This code will automatically change the file to executable if the first line contains both "#!" and "/bin/".

After adding either of these recipies to your editor startup file you should be able to run "emacs test.sh", or "vim test.sh". Once you add #!/bin/sh to the start of the file and save it, the file will be immediately executable and runnable.


This article can be found online at the Debian Administration website at the following bookmarkable URL (along with associated comments):

This article is copyright 2007 Steve - please ask for permission to republish or translate.