1

We have a script that actually does git fetch; git checkout origin/<branch> to deploy a certain feature. The reason why we do this is that we wan't to avoid local branches (it's a test server), so the script just fetch the latest changes and checkout into it, then reloads the server.

We also generate a log describing every deploy made, to bt sent by email to someone and archive. It's interesting that we send also the branch deployed, but the problem is when we do checkout origin/<branch>, we're changing to a detached head. I read some answers with a similar question, but nothing so specific.

Is there a way to print what branch I am in this case (regardless user input, of course)?

Community
  • 1
  • 1
Lucas Sampaio
  • 1,568
  • 2
  • 18
  • 36
  • 1
    [**have a look here**](http://stackoverflow.com/questions/6059336/what-is-the-simplest-way-to-find-the-current-git-branch-name-when-in-detached-he). BTW what is the rationale behind not doing a checkout -b? Ok it's a test server, so what? – Sébastien Dawans Jun 06 '13 at 20:20
  • Actually we don't have any reasons in special. It's just to not maintain actual branches locally (and eventually write code to clean it). But we're open to suggestions, though. – Lucas Sampaio Jun 06 '13 at 20:22

3 Answers3

6

git symbolic-ref --short HEAD should tell you what branch you are on, or print an error if you are not on a branch.

twalberg
  • 59,951
  • 11
  • 89
  • 84
  • This option prints an error for us, but `git show -s --pretty=%d HEAD` is working pretty fine. – Lucas Sampaio Jun 06 '13 at 20:29
  • What error? Perhaps you have an older version of `git`, but I think the above has been around for a while. Your `get show ...` is another option if you don't mind the extra little bit of parsing (or if it's for human eyes only...). – twalberg Jun 06 '13 at 20:32
  • checking out a remote branch gets you a detached head, i.e. a no-branch checkout. `symbolic-ref` is guaranteed to fail after that. – jthill Jun 06 '13 at 22:19
1

Here's git nthlastcheckout, it gets the exact string you used (or everything after its last space) for your nth last checkout from the reflog:

git config --global alias.nthlastcheckout '!nthlastcheckout'"() {
        git reflog |
        awk '\$3==\"checkout:\" {++n}
             n=='\${1-1}' {print \$NF; exit}
             END {exit n!='\${1-1}'}'
}; nthlastcheckout \"\$@\""

Examples:

$ git nthlastcheckout
master
$ git nthlastcheckout 2
v1.3.0^2
jthill
  • 55,082
  • 5
  • 77
  • 137
0

The best solution for us, pointed by @SébastienDawans, was git show -s --pretty=%d HEAD. The output is like remotes/origin/<branch name>, so maybe a cleaning is required, but for our needs it's just fine.

Community
  • 1
  • 1
Lucas Sampaio
  • 1,568
  • 2
  • 18
  • 36