Git 2.43 拉下来的 .sh 报 bad interpreter:换行符怎么批量清

Git 2.43 装在 Windows 上,Core.autocrlf 是 true,仓库里的 deploy.sh 检出后每行结尾都变成 CRLF。在 Git Bash 里执行 bash deploy.sh,报 /bin/bash^M: bad interpreter: No such file or directory,看着像 bash 没装。

文件头是 #!/bin/bash 后面跟了一个 \r,内核去找解释器时把 \r 当成路径的一部分,自然找不到。直接 ./deploy.sh 报得更直白,$'\r': command not found,错在第 3 行的 if 语句上。

先试 dos2unix,Git Bash 里没这个命令;用 sed -i 's/\r$//' 单改一个文件能用,但同事下次 pull 又变回去,等于没修,出问题的文件也从 1 个变成 6 个。

根上的修法是 .gitattributes 里加 *.sh text eol=lf,再 git add --renormalize . 把索引重写一遍,提交后所有人检出都是 LF。已经克隆的仓库要删掉本地文件重新 checkout 才生效,只 pull 不动索引里的旧换行。

之前在 CI 上加过一步 dos2unix,治标不治本,构建机是干净的,问题只出在开发机的检出环节。

确认口径:file deploy.sh 输出 ASCII text 而不是 with CRLF line termiNATors;od -c deploy.sh | head -3 里看不到 \r;在 WSL 和 Git Bash 各跑一次,退出码都是 0。

*.sh text eol=lf
git add --renormalize .
git ls-files --eol deploy.sh

您可以还会对下面的文章感兴趣: