//View Tip #858
Similar Tips
» Sudo from vim to write file
» Quickly empty a file in vi
» Making vim oneliners

 

Latest tips by RSS
Click here to subscribe
Follow Shell-Fu on Twitter
Click here to follow
Follow Shell-Fu on identi.ca
Click here to follow
If you spend a lot of time creating new shell scripts then it can be very useful to make them executable by default. To do this 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/".

Once you add #!/bin/sh (for example) to the start of a file and save it, the file will be immediately executable.


View Comments »




Comments 

Add your comment

Comments are currently disabled
Itamar S
For some reason the shell interperts everything after the !, so I get from bash "endif: command not found". Any ideas?
Posted 2009-07-15 10:50:13
jmao
怎么订阅用mail
Posted 2009-08-13 09:02:47
troy
Had the same problem as Itamar (vim 7).

Fixed it by adding "execute" and quoting the command. Like this,

au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent execute "!chmod a+x <afile>" | endif | endif

that did it for me.
Posted 2009-10-28 08:50:04

Home Latest Browse Top 25 Random Hall Of Fame Contact Submit