Reputation: 15830
I would like my command prompt to display the current branch in my Prompt String 1 (PS1). The command works in git repositories, but when not in a git repo, I get the rightful error message: fatal: Not a git repository (or any of the parent directories): .git
I would like to suppress that error message otherwise every time I switch directories and I am not in a git repo, that error is printed to the terminal.
I read up on suppressing terminal output by sending error output to the null device /dev/null
, but the error message still prints in my terminal.
Here is the command I am using to extract the current branch:
git branch 2>/dev/null | grep '*' | cut -d ' ' -f2
.
Upvotes: 3
Views: 811
Reputation: 6937
Make sure to escape the $
in the $()
construct, so that it will be evaluated anew when each prompt is generated instead of only when the PS1 variable is set.
Here's what it looks like for me in practice:
# Set PS1
$ PS1="\$(git branch 2>/dev/null | grep '*' | cut -d ' ' -f 2) $ "
# Currently in directory that is not a Git repository, change into one.
$ cd dotfiles/
# Git branch is then displayed in the prompt, leave the directory.
master $ cd ..
# No git branch displayed, change back into it for good measure.
$ cd dotfiles/
# Branch is displayed again.
master $
Upvotes: 4