July 18 2014
Git Tip: Auto completion in Terminal
I use Terminal for Git on my Mac. I know there are well-crafted app alternatives like GitHub for Mac and SourceTree, but Terminal works quite well. Except for branch names. Until this week, I had a terrible workflow for switching branches:
- git status – Check the working copy just in case.
- git branch – List all branches to get all branch names.
- Use my cursor to select a new branch’s name. Copy.
- git checkout – Type that then paste the branch name.
Step 3 is bad. I use the cursor and interrupt typing. I could attempt to type the branch name, but with long descriptive ones that include bug numbers, it gets quite frustrating to be off by a letter or number a couple times in a row. And as I discovered this week, there is a better way: Git auto-completion.
I already had Terminal aliases like gs for git status and gl for git log (with a better log). But somehow, I missed the convenient, drop-in Git shell scripts that allow you to auto-complete commands and even branch names in Terminal for bash, tcsh, and zsh.
Here’s how to integrate the bash version:
- Download the script.
- Name it ~/.git-completion.bash.
- Add source ~/.git-completion.bash to ~/.bash_profile.
- Relaunch Terminal.
Now you can tab to auto-complete branch names. The first time I did this, I saw far more branch names than I was expecting, branches that I thought I had deleted. Well, I had, but I hadn’t pruned. Run git remote prune origin to clean those up, and you’re good to go.