Making shell scripts executable via editor hooks

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):

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.

in .vimrc or else I was getting an error about the mode of the file changing... It's also giving two "/bin/bash: endif: command not found" errors. Taking out the two endif statements seems to take care of the error but I'm not really sure this is the right thing to do as I don't really know .vimrc that well...