Reputation: 191779
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:
stderr
and stdout
to null
via 2>/dev/null > /dev/null
Upvotes: 2
Views: 375
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
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
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