Linux · 2 分钟阅读
Shell 脚本自动生成头注释
2026 年更主流的做法:用
cookiecutter/copier起项目模板,Vim 自动头部只是"个人 hack"。但对"打开 .sh 就想看到作者、日期"这件事,Vim 配置仍然好使。
Vim 配置
" ~/.vimrc
set ignorecase
set cursorline
set autoindent
autocmd BufNewFile *.sh call SetShellHeader()
func! SetShellHeader()
if expand('%:e') ==# 'sh'
call setline(1, "#!/bin/bash")
call setline(2, "#********************************************************************")
call setline(3, "#Author: " . $AUTHOR)
call setline(4, "#Date: " . strftime("%Y-%m-%d"))
call setline(5, "#FileName: " . expand("%"))
call setline(6, "#Description: ")
call setline(7, "#********************************************************************")
call setline(8, "")
endif
endfunc
autocmd BufNewFile * normal G
$AUTHOR是环境变量,提前export AUTHOR=YourName即可。
效果
新建 test.sh 后自动长这样:
#!/bin/bash
#********************************************************************
#Author: zhangsan
#Date: 2026-08-04
#FileName: test.sh
#Description:
#********************************************************************
现代替代:cookiecutter
uv pip install cookiecutter
cookiecutter https://github.com/your-org/sh-script-template
模板里把作者、License、CI 占位都填好,一次成型。
现代替代:Neovim snippet
Neovim 用 LuaSnip 配 snippet,写 .sh 时敲 header<Tab> 就能展开:
-- ~/.config/nvim/lua/snippets/sh.lua
return {
s("header", {
t({"#!/bin/bash",
"#*****************************************",
"# Author: " .. vim.env.USER,
"# Date: " .. os.date("%Y-%m-%d"),
"# File: " .. vim.fn.expand("%"),
"#*****************************************"}),
})
}
一些经验
- 注释模板因团队而异:把模板放进 Git,约定俗成
- 头部包含 License、SPDX 标识会更专业
- 自动生成别覆盖已写内容的文件——
BufNewFile触发而不是BufRead - 写好模板后
source ~/.vimrc才生效