darksky
darksky

Reputation: 21019

Git Branch Bash Variable Shortcut

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

Upvotes: 2

Views: 413

Answers (1)

rob mayoff
rob mayoff

Reputation: 385580

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.

Upvotes: 3

Related Questions