Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there any way to set +x bit on script while creating?

For example I run:

vim -some_option_to_make_file_executable script.sh

and after saving I can run file without any additional movings.

ps. I can run chmod from vim or even from console itself, but this is a little annoying, cause vim suggests to reload file. Also it's annoying to type chmod command every time. pps. It would be great to make it depending on file extension (I don't need executable .txt :-) )

share|improve this question
up vote 12 down vote accepted

I don't recall where I found this, but I use the following in my ~/.vimrc

" Set scripts to be executable from the shell
au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod +x <afile> | endif | endif

The command automatically sets the executable bit if the first line starts with "#!" or contains "/bin/".

share|improve this answer
1  
Wow, that's great thing. Btw, seems you can join two if's into one if getline(1) =~ "^#!/bin/". Anyway that's amazing. Thank you. – rush Jun 4 '12 at 13:39
    
This is not a "or". I prefer to use just first condition, au BufWritePost * if getline(1) =~ "^#!" | silent !chmod +x % | endif – vault Feb 17 at 14:39
1  
@rush The reasons for the double if statements is to to catch lines where the the /bin doesn't immediately follow the shebang, like #!/usr/bin/env. A way around that is of course to use a wildcard: getline(1) =~ "^#!.*/bin/". – Harald Nordgren Apr 2 at 14:47

I found this script at http://vim.wikia.com. Not a perfect solution, but a acceptable one, I think.

function! SetExecutableBit()
  let fname = expand("%:p")
  checktime
  execute "au FileChangedShell " . fname . " :echo"
  silent !chmod a+x %
  checktime
  execute "au! FileChangedShell " . fname
endfunction
command! Xbit call SetExecutableBit()

You can now set the execute bit with the command :Xbit. All credit to Max Ischenko at vim.wikia.com

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.