vim:使用+x位创建文件

vim:使用+x位创建文件

有没有办法+x在创建时在脚本上设置位?

例如我运行:

vim -some_option_to_make_file_executable script.sh

保存后我可以运行文件而无需任何额外的移动。

附注我可以chmod从控制台本身运行vim,甚至可以从控制台本身运行,但这有点烦人,因为vim建议重新加载文件。而且chmod每次都输入命令很烦人。 pps。根据文件扩展名来制作它会很棒(我不需要可执行文件.txt:-))

答案1

我不记得在哪里找到这个,但我在 ~/.vimrc 中使用了以下内容

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

如果第一行以“#!”开头,该命令会自动设置可执行位或包含“/bin/”。

答案2

我发现这个脚本http://vim.wikia.com。我认为这不是一个完美的解决方案,但可以接受。

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()

您现在可以使用命令设置执行位:Xbit。全部归功于 vim.wikia.com 上的 Max Ischenko

答案3

我自己写了一个更具选择性的版本。它仅在写入新文件时才使文件可执行,并且仅当该文件以#!.这个版本还避免了执行外部命令,一切都在纯 vim 脚本中完成。

" automatically make script files executable when writing for the first time
function! NewScriptExec() abort
    " check if this is a new file which starts with a shebang
    if exists('s:new_file') && getline(1)[0:1] == '#!'
        " based on https://stackoverflow.com/a/57539332/370695
        let l:file = expand('%')
        let l:old_perm = getfperm(l:file)
        " set the exec bit everywhere the read bit is set
        let l:new_perm = substitute(l:old_perm, '\v(r.)-', '\1x', 'g')
        if (l:old_perm != l:new_perm)
            call setfperm(l:file, l:new_perm)
        endif
        unlet s:new_file
    endif
endfunction

augroup new_script_exec
        autocmd!
        autocmd BufNewFile * let s:new_file = 1
        autocmd BufWritePost * call NewScriptExec()
augroup END

答案4

tonymac的答案在某些时候不再对我有用(使用VIM 7.4),给我带来了与@StevieD相同的问题。修改它解决了问题:

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

我找到了答案https://bbs.archlinux.org/viewtopic.php?id=126304,虽然@StevieD也给出了相同的答案。

相关内容