首页 > 解决方案 > 如何显示 git 分支名称,然后附加引号或取消换行符?

问题描述

如何git branch --show-current停止添加换行符或在换行符之前插入引号?我想通过类似的东西创建一个C风格的头文件

echo -n "#define GIT_LAST_HASH \"" >> TimestampNow.h
git log --no-show-signature -n 1 --format=%h%x22 >> TimestampNow.h # works well
echo -n "#define GIT_BRANCH \"" >> TimestampNow.h
git branch --show-current --format=%x22  >> TimestampNow.h # does not work

去创造

#define GIT_LAST_HASH "1e3134d" // works fine
#define GIT_LAST_BRANCH "develop" // can neither insert quotemark, nor stop newline, at end of 'develop'

标签: gitbranch

解决方案


你无法从中得到你想要的东西git branch --show-current,但幸运的是,你不需要这样做。您已经在使用 shell,所以只需更有效地使用它:

hash=$(git rev-parse --short HEAD)
branch=$(git branch --show-current)  # empty for detached HEAD
printf '#define GIT_LAST_HASH "%s"\n#define GIT_BRANCH "%s"\n' $hash "$branch" >> TimestampNow.h

(顺便说一句,大多数人发现最好使用git describe,而不是像这样拼凑一些东西来制作可用于描述构建的可打印字符串。考虑使用git describe --always --dirty例如。)


推荐阅读