Explosion Pills
Explosion Pills

Reputation: 191779

git branch with no commits

You would think this would not be a common use case, but I create new git repos pretty frequently. Essentially, I have a shell script that stores the current branch into $CURRENT_BRANCH via:

#!/bin/sh -e
git rev-parse --is-inside-work-tree 2>/dev/null > /dev/null
git rev-parse --abbrev-ref HEAD

This works well, even in non-git repos (which is the idea). However, one case where it complains a lot is a git repo that has no commits. Specificially I get:

fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this: 'git [...] -- [...]'

This raises at least two questions:

  1. Why does this error display even though I am redirecting both stderr and stdout to null via 2>/dev/null > /dev/null
  2. How can I get the current branch name even if there are no commits?

Upvotes: 2

Views: 375

Answers (3)

jthill
jthill

Reputation: 60433

In an empty repo, HEAD is attached to a branch that doesn't exist, so git rev-parse can't get a rev [that explanation isn't necessarily what causes the code to complain]. But git symbolic-ref doesn't ever care about the SHA, so

git symbolic-ref -q --short HEAD || echo HEAD

with an attached HEAD won't look any farther than that, but the git symbolic-ref fails if HEAD's not attached to a branch so the echo preserves your current behavior.

Upvotes: 3

Mayur Nagekar
Mayur Nagekar

Reputation: 811

What kind of repository you have created ? Is it a bare repository and is it that you are running these commands in the bare repository? Does running "git branch" show you any branch ?

In a bare repository, it won't fetch you any useful information and is not advisable to run any direct operation in it.Ideally, I would clone a bare repository and then do an empty commit in it to get started so that the branch name appears(by default "master") would be created. Now if you wish change the name of branch. Coming to you errors you faced, I could reproduce it at my end when I cloned a bare repository and had not created any branch in it.

Or, did you create an orphan branch when you faced this issue.

Upvotes: 0

flx
flx

Reputation: 14226

Why not using the __git_ps1 command?
It was initially made to add these kind of information to PS1, nut you can use it from prompt as well.

I'm using this to show the current git branch in my prompt:

PS1="\$(__git_ps1 '(%s) ')${PS1}"

Just call this to print the current branch:

__git_ps1 '%s\n'

The argument is a formatted string. %s gets replaced by the branch's name.
The command does not give any output, if $PWD is not inside a git repo.

You need git's bash-completion to have that version defined. It's located here /usr/lib/git-core/git-sh-prompt.

Upvotes: 0

Related Questions