Question: 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?

Answer: 
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.
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`.