Tip: #709 - Simple creation of scripts
Created: May 2, 2004 23:39 Complexity: basic Author: Yakov Lerner <jilerner--AT--yahoo.com> Version: 6.0 Karma: 53/26 Imported from: Tip#709
If you create lot of shell scripts, then you'll find this useful:
" automatically give executable permissions if filename is *.sh au BufWritePost *.sh :!chmod a+x <afile> " automatically insert "#!/bin/sh" line for *.sh files au BufEnter *.sh if getline(1) == "" | :call setline(1, "#!/bin/sh") | endif " automatically give executable permissions if file begins with #!/bin/sh au BufWritePost * if getline(1) =~ "^#!/bin/[a-z]*sh" | silent !chmod a+x <afile> | endif
Yakov Lerner
Comments
Cool Tip! I adopted it for python files:
au BufEnter *.py if getline(1) == "" | :call setline(1, "#!/usr/bin/env python") | endif
Might be useful for other languages as well, maybe an idea for a plugin for multiple languages.
André
fs111 at web dot de , May 3, 2004 4:20
Here's something a little better for python:
" Python header function! <SID>PythonHeader() :call setline(1, "#! /bin/sh") :call append(1, "# vim: filetype=python") :call append(2, "\"\"\":\"") :call append(3, "exec python $0 ${1+\"$--AT--\"}") :call append(4, "\"\"\"") :call append(5, "") exe 6 endfunction au BufEnter *.py if getline(1) == "" | call s:PythonHeader() | endif
Or for shell:
" Shell header function! <SID>ShellHeader() :call setline(1, "#! /bin/sh") :call append(1, "") exe 2 endfunction au BufEnter *.sh if getline(1) == "" | call s:ShellHeader() | endif
ahern--AT--deskmedia.com , May 6, 2004 14:18
The last line of the expression do somethink wrong on my .vimrc. After
au BufWritePost * if getline(1) =~ "^#! ?/bin/[a-z]*sh" | silent !chmod a+x <afile> | endif
a following
au BufWritePost *.pl :silent !chmod a+x <afile>
will never been executed. It seems that the endif in the line bevor will not be find.
Any clue?
K.Ethgen--AT--gmx.de , May 22, 2004 23:45
I did not want the script to keep doing the chmod even when the file is already excutable, so this is what I have in my .vimrc:
" Define a function that can tell me if a file is executable function! FileExecutable (fname) execute "silent! ! test -x" a:fname return v:shell_error endfunction " Automatically make Perl and Shell scripts executable if they aren't already au BufWritePost *.sh,*.pl,*.cgi if FileExecutable("%:p") | :!chmod a+x % ^--AT-- endif
Note that the ^--AT-- is actually Ctrl-V Ctrl-J (an imbedded new line), because you cannot use | as a separator after an external command.
mpbrownfield--AT--fedex.com , July 22, 2004 10:54
For the problem with " | endif" after a shell command - e.g.:
au BufWritePost * if getline(1) =~ "^#! ?/bin/[a-z]*sh" | silent !chmod a+x <afile> | endif I noticed that the above works fine for csh / tcsh, but not in a bash shell. I got this to work fine for a bash shell: au BufWritePost * if getline(1) =~ "^#! ?/bin/[a-z]*sh" | silent !chmod a+x <afile> au BufWritePost * | endif
HTH.
cj a t nologic d o t org , August 24, 2006 9:07