DEV Community

Cover image for Git [Script] Aliases That Could Be Helpful
Krishna  Damaraju
Krishna Damaraju

Posted on • Updated on

Git [Script] Aliases That Could Be Helpful

Usage of terminal is one of the best things a programmer does. It makes us feel like a little hacker playing around (at-least to me ;D ) with his cozy tool. We write little tools (when ever possible) to automate small tasks or cut the pain of typing a very long commands.

Git has the awesome feature of writing your own aliases to commands. I like it a lot and written a set of aliases that I use everyday (I call them short-codes) and I wanted to share them hoping to-be useful to others.

And it starts here ..

These are the list of aliases that I use everyday.

alias g!='git init' 
alias g.='git add .'
alias g.-file='git add'
alias gb='git branch'
alias gb-new='git checkout -b'
alias gblame='git blame'
alias gcl='git clone'
alias gc='git commit -m'
alias gcout='git checkout'
alias gd='git diff'
alias gf='git fetch'
alias gl='git log'
alias gph='git push'
alias gph-f='git push -f'
alias gpl='git pull'
alias gr='git remote'
alias gr-list='git remote -v'
alias gr-add='git remote add'
alias greset='git reset --hard'
alias grevert-head='git revert HEAD'
alias grevert='git revert'
alias gs='git status'
alias gsh='git stash'
alias gsh-a='git stash apply'
alias gsh-c='git stash clear'
alias gsh-d='git stash drop'
alias gsh-l='git stash list'
alias gsh-p='git stash pop'

If you feel they are helpful, you can create your own aliases with the above list or I have created a git repo with detailed instructions to install and use them.

Make sure to reopen your terminal to see the changes.

Update: I'd recommend beginners to learn and understand actual commands before using any tools/aliases for git.


Top comments (33)

Collapse
 
val_baca profile image
Valentin Baca • Edited

To be a little nitpicky, those are technically shell aliases to git, not actually git aliases.
However, the link you included shows how to use git aliases.

I'd actually recommend against making a ton of shell aliases as they don't possess the full power that doing real git aliases can provide.

You can also run into trouble if you try to combine shell scripts with git. If you use real git aliases, you can use the aliases, but if you use shell aliases, you cannot.

Instead, I just do this single shell alias: alias g=git

Then include all the git aliases you want in ~/.gitconfig.

To execute, you just do:

$ g st # same as git status, the shell maps g -> git and git maps st -> status

Here's a large chunk of my ~/.gitconfig:

[alias]
    git = !exec git
    f = !git fetch || echo "Gretchen, stop trying to make fetch happen\\!"
    st = status --short --branch
    n = number
    # number, short
    nu = number --column -s
    # number, full status
    ns = number --column
    # number command, e.g. git number -c vim 1 # opens file 1 in vim!
    nc = number -c
    nvi = number -c vim
    na = number add
    si = status --ignored
    ci = commit
    co = checkout
    br = branch
    df = diff
    dc = diff --cached
    dn = diff --name-only
    dw = diff --color-words
    sq = merge --squash
    cob = checkout -b
    # quick add all and commit with message
    cm = commit -a -m
    ammend = commit --ammend
    # safer than just doing git reset HEAD --hard. we can restore using git reflog
    wipe = !git add -A && git commit -qm 'WIPE SAVEPOINT' && git reset HEAD~1 --hard
    llog = log --oneline @{upstream}..HEAD
    llp = log -p @{upstream}..HEAD
    lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative
    # log tree
    lt = log --graph --simplify-by-decoration --pretty=format:'%d' --all
    # log list
    ls = log --pretty=format:"%C(yellow)%h%Cred%d\\ %Creset%s%Cblue\\ [%cn]" --decorate
    # longer log list
    ll = log --pretty=format:"%C(yellow)%h%Cred%d\\ %Creset%s%Cblue\\ [%cn]" --decorate --numstat
    # log list no color
    lnc = log --pretty=format:"%h\\ %s\\ [%cn]"
    # log oneline with dates
    lds = log --pretty=format:"%C(yellow)%h\\ %ad%Cred%d\\ %Creset%s%Cblue\\ [%cn]" --decorate --date=short
    # short git log
    le = log --oneline --decorate
    # quick good log
    l = log --graph --oneline --decorate --date=relative --all
    # filelog
    filelog = log -u
    fl = log -u
    # diff last commit
    dlc = diff --cached HEAD~1
    pr = pull --rebase
    pro = pull --rebase origin
    prom = pull --rebase origin mainline
    dag = log --graph --format='format:%C(yellow)%h%C(reset) %C(blue)\"%an\" <%ae>%C(reset) %C(magenta)%ar%C(reset)%C(auto)%d%C(reset)%n%s' --date-order
    dfn = diff --name-only
    diffn = diff --name-only
    permission-reset = !git diff -p -R | grep -E \"^(diff|(old|new) mode)\" | git apply
    # searches through all commits
    supergrep = !git rev-list --all | xargs git grep
    fo = fetch origin
    # show recent branches
    recent = for-each-ref --count=10 --sort=-committerdate refs/heads/ --format="%(refname:short)"

    scan = "!git clean -nx && git clean -ndx"
    nuke = "!git clean -fx && git clean -fdx"

Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju

Thanks for the detailed explanation Valentin. I wanted to write a bash script for git aliases so that I could learn both bash and git. That was my requirement and I guess it is time to make the changes to the my little code snippet.

Collapse
 
itsasine profile image
ItsASine (Kayla)

f = !git fetch || echo "Gretchen, stop trying to make fetch happen\!"

I'm stealing this

Collapse
 
sublimegeek profile image
Jonathan Irvin

Dang. There is such a thing as too many Git aliases. Seems to me that after a certain point, unless you have them all memorized, you'd start running into diminishing returns.

Collapse
 
val_baca profile image
Valentin Baca

I don't use all of them and by no means have them all memorized.

For the most part, they're just acronyms: 'dw' == 'diff words'.

I also kind of use my git alias file as place to keep notes for commands.

You should see my shell alias file :P I like to joke that I hate typing.

Collapse
 
ben profile image
Ben Halpern

Thanks for the clarifying comment.

Collapse
 
maxgoldst profile image
Max Goldstein

Please, please use git push --force-with-lease instead of -f or --force.

Like all things git, the naming (a lease?) is a bit wonky. But basically, it will only do the forcing behavior when your local copy of the remote (e.g. GitHub) is up to date. It will refuse to overwrite commits that you haven't seen. This is much safer.

Collapse
 
sebastientorres profile image
sebastientorres

I like the gs and gd alias, as I would use those a lot.

One I copied from a colleague:
lg=log --graph --all --date=local --format=format:'%C(cyan)%h%C(reset) - %C(red)%d%C(reset) - %C(white)(%ai)%C(reset) %C(white dim)%s%C(reset) %C(white) -- %an%C(reset)' --abbrev-commit --color

One that I expanded the above to:
lge=log --graph --all --date=local --name-status --format=format:'%C(cyan)%h%C(reset) - %C(red)%d%C(reset) - %C(white)(%ai)%C(reset) %C(white dim)%s%C(reset) %C(white) -- %an%C(reset)' --abbrev-commit --color

Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju

Great, I remember following pretty graphs for git and saw similar on Stack Overflow but never got a chance to try it. Will check it now.

Collapse
 
sebastientorres profile image
sebastientorres

:-) Glad to suggest and contribute.

Thread Thread
 
sarathsantoshdamaraju profile image
Krishna Damaraju • Edited

Sure, If you want, you can raise a PR in repo with your own aliases.

Collapse
 
bgadrian profile image
Adrian B.G. • Edited

bash-it would solve some of the problems of using your own made-up aliases (git or bash) (like other devs being familiar with them).

Recently I removed my own old aliases I got used over the years and got familiar with bash-it pretty quickly (they have a logic and once I got it I repeat the full command in my head but only type the first letters like "Git Commit All Message is gcam".
Git is only one plugin of the bash-it framework, I recommend to check it out.

Collapse
 
c4augustus profile image
Christopher Augustus

As convenient as shell aliases can be, familiarity with the actual git commands and arguments help us stay sharp. Additionally if you are helping someone else on their computer or yours, they won't understand your commands or learn anything from them--unless they are using the same aliases.

I worked for a customer that built their own custom configuration management solution to make it easier to use git. This had the effect of weakening developers' ability to cope with git directly. Anytime they confronted atypical use scenarios (e.g. resolving merge conflicts) they were fairly helpless to resolve it.

IMO, knowing git well is one of the most important skills any current developer should have. Unlike programming languages, we now have the great benefit of a single dominant tool for version control--thankfully an open source one. The stronger you are with git, the more productive you will be.

Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju • Edited

Yes, git is an important skill to any developer. I agree with the points you have mentioned, but one can always use the git commands if they feel aliases are not helping. These will work as just a convenience for anyone to speed up the VC tasks and I personally don't prefer to use GUI tools available for git (despite their benefits) so settled with the aliases.

Collapse
 
rob117 profile image
Rob Sherling

"but IMO it is not related to productivity"

  • Could you explain this a bit more?
Collapse
 
arun2789 profile image
Arun Srinivasan

That's a lot of aliases! :) I stick to writing the full command, out of fear that I may eventually forget the actual, and just know the alias!

Nice post, Sarath.

Arun.

Collapse
 
pmcgowan profile image
p-mcgowan • Edited

Thought I'd chime in - never looked into git aliases much, but I made a bash script containing all my helper commands a while back when I was learning git, and since moved them into bash aliases for ones I use frequently. At this point, they are just convenience since I know the base commands, so I would recommend learning the underlying commands first, but these are just lazy helper aliases.

alias gst='git status'
# Git log
glog() {
  case $1 in
    -s | --short | s)
      git log --pretty=format:'%h %ad | %s%d [%an]' $colour --graph --date=short;;
    -d | --diff | d)
      git log -p;;
    -f | --from | f)
      shaOrDate="$2"
      if [[ "$shaOrDate" =~ ^[[:alnum:]]{40}$ ]] || [[ $shaOrDate =~ ^[[:alnum:]]{6}$ ]]; then
        cmd="$shaOrDate^..$(git rev-parse HEAD)"
        # Could add --to=$3
        # cmd="$shaOrDate^..${3-$(git rev-parse HEAD)}"
      elif [[ "$shaOrDate" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
        cmd="--since $shaOrDate"
      else
        echo "Unsupported bound: '$2'"
        echo "Expecting SHA hash (6 or 40 chars) or date YYYY-MM-DD"
        return 1
      fi
      git log $cmd --date=short --pretty=format:'%h %ad %an | %s%d'
    ;;
    -h | --help | h)
      echo "glog [-s | --short | -d | --diff | -h | --help] [-f | --from [SHA or date]]";;

    *)
      git log -p --stat --graph;;
  esac
}

alias gmerge='git merge --no-ff'

gpull() {
  branch=${1-$(git branch |grep '\*' |sed 's/\*\ //g')}
  remote=$(git remote |tail -n1)
  echo Pulling from $remote $branch
  git pull $remote $branch
}

gpush() {
  branch=${1-$(git branch |grep '\*' |sed 's/\*\ //g')}
  remote=$(git remote |tail -n1)
  echo Pushing to $remote $branch
  git push $remote $branch
}

gcam() {
  git add -A
  git commit -am "$*"
}

gcpush() {
  git add -A
  git commit -am "$*"
  gpush
}

# Edit merge conflicts - tries to use sub (may me subl on yours) or vim
geditmerge() {
  if [ -n "$(which sub)" ]; then
    editor=sub
  else
    editor=vim
  fi
  toedit=$(git diff --name-only --diff-filter=U)
  $editor $toedit
}
Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju • Edited

Exactly, even for me they are just convenience, I'd never recommend them for beginners. Why did I forget to mention it in the post? Will do it now.

Collapse
 
pmcgowan profile image
p-mcgowan

Bash was built for convenience... Almost every script / alias / program I write is simply to make my life easier.

I'm lazy, so I have aliases like .. for cd .. and ... for cd ../.. etc, bashrc for source ~/.bashrc, ebashrc for vim ~/.bashrc... If I type it regularly enough, sooner or later it will be "functioned/aliased". Any time I have to use Windows or Mac I cry a little.

Collapse
 
nickytonline profile image
Nick Taylor • Edited

Love git aliases, but as Valentin said they're shell aliases. Regardless, shell aliases and git aliases are very useful. Here's my list of git aliases if your interested.

One shell alias that find very helpful is for grabbing a PR from a repo hosted on GitHub (maybe it works on BitBucket too, not sure).

# Check out a PR
alias copr="git fetch origin pull/$argv/head:pr$argv; and git checkout pr$argv;"
funcsave copr

This is a fish shell alias, but I think you get the idea.

Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju

Thanks Nick, I have seen a couple of aliases that could be helpful to me form your gist, will add them soon

Collapse
 
dance2die profile image
Sung M. Kim

Any other Windows users who knows how to alias those git commands by chance?

Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju • Edited

Found this that could be helpful to you to write your now git script aliases
gist.github.com/wzup/36b5159d8c580...

Collapse
 
dance2die profile image
Sung M. Kim

Oh nice!
Thanks Sarath.
I installed bash on Windows 10 recently and seems like a good way to try it out :)

Collapse
 
sublimegeek profile image
Jonathan Irvin

I just wrote an article on git aliases. Teaching Git Some New Tricks

I won't rehash what others have said about bash aliases versus Git aliases, but I do second the point that you should learn to walk before you run and understand what a Git command does before making aliases.

Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju

Yes, that is why I don't recommend this for beginners !

Collapse
 
moopet profile image
Ben Sinclair

I find these extremely short aliases hard to use. "gsh-p" is harder to type than "git stash pop" because I have to hit the dash. "g!" means nothing to me and is just another thing to try to remember.
Maybe if I used "git init" a couple of hundred times a day it would be worth committing an alias to memory, but my brain's already too full!

Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju

Yes, because I have written them for my convenience. So feel fee to write them with your own.

Collapse
 
serajam profile image
Fedir Petryk

Nice :)

Collapse
 
sebastientorres profile image
sebastientorres

gsh-d and gsh-p are the same, is gsh-p meant to be 'git stash pop'?

Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju

Thanks, it was a bug. Fixed it

Collapse
 
chrisvasqm profile image
Christian Vasquez

This is awesome!

Collapse
 
sarathsantoshdamaraju profile image
Krishna Damaraju

Glad you liked 'em