Home > Software engineering >  How do I display a git branch name, then either append a quotemark, or suppress newline?
How do I display a git branch name, then either append a quotemark, or suppress newline?

Time:10-31

How do I get git branch --show-current to either stop appending a newline, or to insert a quotemark before the newline? I want to create a C-style header file via something like

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

to create

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

CodePudding user response:

You can't get what you want from git branch --show-current, but fortunately, you don't need to do that. You're already using the shell, so just use it more effectively:

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

(Incidentally, most people find it's best to use git describe, rather than piecing things together like this, to make a printable string that can be used to describe a build. Consider using git describe --always --dirty for instance.)

  • Related