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

如何让git branch --show-current不追加换行或在换行前插入引号

问题原因

你原有命令失效有两个核心原因:

  • git branch的--format参数无法和--show-current参数搭配使用,你设置的%x22(双引号)不会生效
  • git branch --show-current默认输出会在分支名末尾自动携带换行符,直接拼接会导致引号被挤到下一行

解决方案

推荐两种可行实现方式:

方式1:调整原有git branch命令(支持git 2.22及以上版本)

将最后两行相关代码替换为以下内容即可:

echo -n "#define GIT_LAST_BRANCH \"" >> TimestampNow.h
echo "$(git branch --show-current)"\" >> TimestampNow.h

方式2:用兼容性更好的git rev-parse命令(支持所有主流git版本)

更推荐这个方案,不需要依赖高版本git的新参数:

echo -n "#define GIT_LAST_BRANCH \"" >> TimestampNow.h
echo "$(git rev-parse --abbrev-ref HEAD)"\" >> TimestampNow.h

实现原理

shell的命令替换语法$()会自动丢弃命令输出末尾的所有换行符,刚好解决你遇到的多余换行问题,之后直接手动拼接双引号即可输出符合预期的格式。

完整脚本示例

# 可选:先清空旧文件避免重复追加
> TimestampNow.h
echo -n "#define GIT_LAST_HASH \"" >> TimestampNow.h
git log --no-show-signature -n 1 --format=%h%x22 >> TimestampNow.h
echo -n "#define GIT_LAST_BRANCH \"" >> TimestampNow.h
echo "$(git rev-parse --abbrev-ref HEAD)"\" >> TimestampNow.h

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:54:04