Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Copy current git branch to clipboard
git branch | grep "*" | awk '{ print $2 }' | pbcopy
@charlieegan3

I found the below worked better for an alias:

alias gitb="git branch | grep '^\*' | cut -d' ' -f2 | pbcopy"
@azizbekian

For those, who don't know how to make this work: create a file, e.g. git_branch_name_to_clipboard.sh in your user directory with following content:

git branch | grep "*" | awk '{ print $2 }' | pbcopy

Then in .gitconfig file, which is located in your user folder, add these lines under [alias]:

cp = "!sh $HOME/git_branch_name_to_clipboard.sh"

Now performing git cp will copy your current branch name to clipboard.

@fengshuo

@lnolte @azizbekian thanks for the tip, I found it very helpful to paste the branch name when I am editing commit messages.
Although there is a new line character at the end of the copied content, I can change it to not move to a new line on Terminal, but when I am using IntelliJ's embed terminal, it doesn't have an option to not move to a new line.
So here is a modified version of the sh file without the new line character in case someone else want to use it:
git branch | grep "*" | awk '{ print $2 }' | tr -d '\n' | pbcopy
Also I am wondering if you know any other tools/tricks to copy paste the current branch :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment