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

如何自动为文件头部添加包含文件路径的注释?

修复Bash脚本:批量为文件头部添加路径注释

原脚本的核心问题

  1. 无效的if分支:第一个if [[ "$file" == *.sh ]]; then后面无执行语句直接接elif,违反Bash语法
  2. 非法变量名:First-line_comment包含连字符,Bash变量名仅允许字母、数字和下划线
  3. 错误的默认分支语法:elif any other file type完全不符合Bash语法规范
  4. 重复赋值覆盖结果:脚本后半段重复赋值First-line_comment="# *$file",直接覆盖前面分支设置的注释格式
  5. 二进制文件未跳过:处理ico/jpg/png等二进制文件时,未加入跳过逻辑,会导致文件损坏
  6. 文件名空格兼容问题:files=$(find $pwd -type f)的写法会把含空格的文件名拆分成多个元素,引发遍历错误

修复后的完整脚本

#!/bin/bash

target_dir="scripts/test_copy-content"

# 用while循环读取find结果,兼容含空格的文件名
find "$target_dir" -type f | while read -r file; do
    # 初始化注释变量
    first_line_comment=""
    
    # 根据文件类型设置对应注释格式
    if [[ "$file" == *.sh ]]; then
        first_line_comment="# *$file"
    elif [[ "$file" == *.go ]]; then
        first_line_comment="# *$file"
    elif [[ "$file" == *.py ]]; then
        first_line_comment="# *$file"
    elif [[ "$file" == *.md ]]; then
        first_line_comment="<!-- *$file -->"
    elif [[ "$file" == *.css ]]; then
        first_line_comment="/* *$file */"
    elif [[ "$file" == *.js ]]; then
        first_line_comment="/* *$file */"
    elif [[ "$file" == *.html ]]; then
        first_line_comment="<!-- *$file -->"
    elif [[ "$file" == *.ico || "$file" == *.jpg || "$file" == *.png ]]; then
        # 跳过二进制文件,直接进入下一次循环
        continue
    elif [[ "$file" == *Makefile ]]; then
        first_line_comment="# *$file"
    elif [[ "$file" == *.own ]]; then
        first_line_comment="<!-- *$file -->"
    else
        # 默认注释格式
        first_line_comment="# *$file"
    fi

    # 兜底:跳过未设置注释的情况
    [[ -z "$first_line_comment" ]] && continue

    # 仅处理文本文件,避免二进制文件乱码或损坏
    if file "$file" | grep -q text; then
        first_line=$(head -n 1 "$file")
        # 检查首行是否已存在目标注释
        if [[ "$first_line" != "$first_line_comment" ]]; then
            # 将注释插入文件头部
            echo -e "$first_line_comment\n$(cat "$file")" > "$file"
        fi
    fi
done

关键修复说明

  • 修正变量命名:把First-line_comment改为first_line_comment,符合Bash变量命名规则
  • 补全空分支:为第一个*.sh分支添加对应的注释赋值
  • 替换默认分支:用标准的else替换错误的elif any other file type
  • 跳过二进制文件:在处理ico/jpg/png时,用continue直接跳过后续操作
  • 兼容文件名空格:改用find | while read -r file的方式遍历文件
  • 增加文本判断:通过file命令识别文本文件,只对文本文件执行注释操作
  • 移除重复赋值:删除后半段覆盖注释变量的冗余代码

内容的提问来源于stack exchange,提问作者Maria Pop

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:05:16