You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Shell查找并删除文件:如何避免代码重复?

优化Zsh脚本以避免代码重复

当然可以通过提取公共逻辑为变量和函数的方式,彻底消除脚本中的重复代码,同时保持原有功能不变。优化后的脚本如下:

#!/usr/bin/env zsh

# 定义要处理的文件扩展名数组(已去除原列表中重复的out项)
local exts=(
    log out aux dvi lof lot bit idx glo bbl bcf ilg toc ind
    blg fdb_latexmk fls run.xml pyg pyg.out
)

# 封装公共处理逻辑:参数为动作(print/delete)
process_files() {
    local action="$1"
    # 遍历扩展名处理对应文件
    for ext in "${exts[@]}"; do
        find . -type f -name "*.$ext" -not -path "./.git/*" "-$action"
    done
    # 处理Tmp目录下的所有文件
    find Tmp/ -type f "-$action"
}

# 提示信息并列出待删除文件
tput bold; tput setaf 1
echo "You are about to DELETE ALL auxillary files and Tmp files"
echo "These are the files to be deleted:"
tput sgr0

process_files print

# 等待用户确认操作
tput setaf 3
read -s -k "?Press any key to purge!"$'\n'
tput sgr0

# 执行删除操作
process_files delete

# 完成提示
tput bold; tput setaf 1
echo "DONE"

关键优化说明

  • 提取扩展名数组:把重复书写的扩展名列表定义为exts数组,后续修改扩展名或规则只需修改这一处,避免多份列表不一致的问题。
  • 封装复用函数:用process_files函数统一处理「列出文件」和「删除文件」的逻辑,通过传入print或delete参数切换行为,彻底消除重复的循环与find命令。
  • 细节优化:去除了原列表中重复的out扩展名,不影响功能的同时让代码更简洁。

内容的提问来源于stack exchange,提问作者Michael Freimann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:25:20