vim: automatically chmod+x for files with shebang

Wouldn’t it be useful, if any shell, python or any other kind of script you edit with vim was set to be executable automatically? Given the file starts with a shebang line, the following vim script does this automatically for you.

Adding this to your .vimrc automatically sets the execution mode-bit when editing files beginning with a shebang #! followed by a path containing “bin”, e.g. #!/bin/bash.


" automatically give executable permissions if file begins with #! and contains '/bin/' in the path
" see http://www.debian-administration.org/articles/571
" modified 23.12.2008 Benedikt Stegmaier
"
function MakeScriptExecuteable()
if getline(1) =~ "^#!.*/bin/"
silent !chmod +x
endif
endfunction

au BufWritePost * call MakeScriptExecuteable()

After a file’s permission have changed, vim will ask you what to do… Hit L to reload the file.

W16: Warning: Mode of file "myscript.sh" has changed since editing started See ":help W16" for more info. [O]K, (L)oad File: 

Edits:

  • 2013-05-02 Migrated this article from my old website
  • 2014-12-16 Again a migration

Leave a Reply

Your email address will not be published. Required fields are marked *