如何并行或懒加载Bash补全文件以加速Shell启动?
解决Bash补全脚本拖慢Shell启动的懒加载方案
针对你频繁启停Shell导致补全加载拖慢启动速度的问题,下面提供几个可行的懒加载方案:
方案1:单个命令触发时懒加载对应补全
给常用命令写一个临时包装函数,第一次执行命令时自动加载其补全脚本,之后直接调用真实命令:
# 以git为例,其他命令可以复制这个结构修改 git() { local comp_script="/usr/share/bash-completion/completions/git" if [ -f "$comp_script" ]; then . "$comp_script" unset -f git # 删除临时函数,后续直接用真实git fi command git "$@" }
把这类函数添加到.bashrc中,只有第一次使用对应命令时才会加载补全,完全不影响Shell启动速度。
方案2:首次Tab补全时批量加载所有补全脚本
通过设置默认补全处理函数,让第一次按下Tab触发补全时才加载所有补全脚本,之后不再重复加载:
lazy_load_all_completions() { # 加载/etc/bash_completion.d下的所有补全脚本 if [ -n "$(find /etc/bash_completion.d -mindepth 1 -maxdepth 1)" ]; then for file in /etc/bash_completion.d/*; do . "$file" 2>/dev/null done fi # 取消默认补全处理函数,避免重复执行加载逻辑 complete -r -D # 恢复正常Tab补全行为 bind '"\t":complete' } # 设置默认补全处理函数为上面的懒加载逻辑 complete -D -F lazy_load_all_completions
把这段代码替换你原来在.bashrc中加载补全的代码即可。Shell启动时完全不加载补全脚本,只有第一次按Tab时才会批量加载,之后补全正常工作。
方案3:预加载常用补全+剩余懒加载
如果不想完全等到第一次Tab才加载,可以预加载几个高频命令的补全脚本,剩下的用方案2的懒加载逻辑:
# 预加载常用命令的补全脚本路径 preload_scripts=( "/usr/share/bash-completion/completions/git" "/usr/share/bash-completion/completions/pacman" "/usr/share/bash-completion/completions/yay" ) # 执行预加载 for script in "${preload_scripts[@]}"; do [ -f "$script" ] && . "$script" 2>/dev/null done # 懒加载剩余补全脚本 lazy_load_remaining_completions() { if [ -n "$(find /etc/bash_completion.d -mindepth 1 -maxdepth 1)" ]; then for file in /etc/bash_completion.d/*; do # 跳过已预加载的脚本(如果/etc/bash_completion.d中有对应链接) if [[ ! " ${preload_scripts[@]} " =~ " $file " ]]; then . "$file" 2>/dev/null fi done fi complete -r -D bind '"\t":complete' } complete -D -F lazy_load_remaining_completions
内容的提问来源于stack exchange,提问作者Carlos González
相关产品推荐
相关产品推荐

