Paul
Paul

Reputation: 4436

Git rev-parse --abbrev-ref HEAD vs branch --show-current differences in a new init project

I took an empty project with just one newly created file, I ran the git init command, when I run the commands below I get the following results:

command:

git rev-parse --abbrev-ref HEAD

output:


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

command:

git branch --show-current

output:

main

I wonder what the correct command in this case to execute, what the correct name of the branch in the current state HEAD or main?

What is the difference between the two commands?

Upvotes: 2

Views: 871

Answers (1)

Romain Valeri
Romain Valeri

Reputation: 21908

Root cause: Your main branch is in fact unborn here.


To give a bit more details,

git rev-parse --abbrev-ref <ref>

tries to recursively search for the commit hash ultimately sitting behind <ref> (which could point to another ref).

In the case of your empty repo, git init has already created a .git/HEAD file, which you can read with cat .git/HEAD which will output ref: refs/heads/main (for some people it might also be ref: refs/heads/master, depending on the config).

However, it's only a temporary ref put in place at repo creation by default. Your first commit will be, unless you explicitly checkout a new branch, on this first default ref.

And regardless of what's written in HEAD, .git/refs/heads/main doesn't already exist until you commit something to it.

The reason git branch --show-current doesn't "fail" but outputs main is that it does not dereference the branch name until commit hash, it only needs a ref name, and finds it in HEAD, unbothered by the emptiness of the ref it actually points to.

Upvotes: 4

Related Questions