2

I am trying to create a bash variable which I can use to refer to my current branch in Git: something like $branch.

When adding: branch=$(git symbolic-ref --short -q HEAD) into my bash_profile, I keep getting: fatal: Not a git repository (or any of the parent directories): .git when I start a new terminal.

Furthermore, echo $branch does not print out the branch name, as git symbolic-ref --short -q HEAD would.

I'd like to be able to use it not to print out the branch name (I already have that in my prompt) but to do things like:

git push origin $branch

1
  • 1
    Don't you just want to use an alias you can call later? Commented Aug 12, 2013 at 22:19

1 Answer 1

3

Which branch you are on depends on which directory you are in. If you have two git work trees, ~/a and ~/b, then typing cd ~/a can put you on one branch and typing cd ~/b can put you on another branch.

So trying to set $branch in your .bash_profile isn't going to work. You need to update $branch every time you change work trees, and after any command that can change the branch of the current work tree.

The simplest thing to do is just not set a variable. Instead, make an alias:

alias branch='git symbolic-ref --short -q HEAD 2>/dev/null'

And then use it like this:

git push origin $(branch)

or like this if you're old-school:

git push origin `branch`

If you really want to set an environment variable, the simplest solution is to just set it every time you print your prompt:

_prompt_command () {
    export branch=$(git symbolic-ref --short -q HEAD 2>/dev/null)
}
export PROMPT_COMMAND=_prompt_command

Note: you should check your .bash_profile and .bashrc to see if you're already setting PROMPT_COMMAND. If so, just set branch in whatever function you're already running as your prompt command.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.