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 🙂 )
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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/”.
Method 2
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
Method 3
I use this in MacVim Custom Version 8.0.648 (134)
" if file is executable just exit
au BufWritePost *.sh if FileExecutable("%") | if getline(1) =~ "^#!" | silent !chmod u+x % | endif | endif
" Determines if file is already executable
function! FileExecutable(fname)
execute "silent! ! test -x" a:fname
return v:shell_error
endfunction
Method 4
tonymac’s answer stopped working for me at some point (with VIM 7.4), giving me the same problem as @StevieD. Modifying it fixed the problem:
au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent execute "!chmod +x <afile>" | endif | endif
I found the answer from https://bbs.archlinux.org/viewtopic.php?id=126304, although @StevieD also gave the same answer.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0