Reputation: 55739
I am using the following to display the current branch name in my bash prompt (via .bash_profile
):
GetBranch()
{
cat ./.git/HEAD | sed 's+^ref: refs/heads/++'
}
But when I am in a directory that does not correspond to a git repository, I get an error (because ./.git/HEAD does not exist
).
How can I suppress this error?
Upvotes: 1
Views: 123
Reputation: 16527
Not directly answering the question, but there are a lot of existing scripts to get a git-aware prompt. You may want to use them instead of writing your own. See for example https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh or search "git bash prompt" in you favorite search engine.
Upvotes: 1
Reputation: 531325
Use git
itself to return the currently checked-out branch, rather than digging into the repository.
GetBranch () {
git symbolic-ref --short HEAD 2> /dev/null
}
This will work from any directory in a repository, not just the root.
Upvotes: 1
Reputation: 25399
Test whether the repository is present first:
GetBranch()
{
if [ -f .git/HEAD ]
then
sed 's+^ref: refs/heads/++' < .git/HEAD
else
echo "Not a repository" >&2
fi
}
Upvotes: 2
Reputation: 20899
Redirect STDERR to /dev/null:
GetBranch()
{
cat ./.git/HEAD 2>/dev/null | sed 's+^ref: refs/heads/++'
}
Here's a quick guide on file descriptors that will help explain how 2>/dev/null
works.
Alternately, instead of suppressing an error, you could make the command conditional on ./.git/HEAD
existing:
GetBranch()
{
if [[ -e "./.git/HEAD" ]]; then
cat ./.git/HEAD 2>/dev/null | sed 's+^ref: refs/heads/++'
fi
}
Upvotes: 2