2

In Pro Git Scott Chacon gives some nice examples of some alias which might be helpful, including one that shows the last commit: git last which is the equivalent of log -1 HEAD:

git config --global alias.last 'log -1 HEAD'

It will show something like this:

$ git last
commit 66938dae3329c7aebe598c2246a8e6af90d04646
Author: Josh Goebel <dreamer3@example.com>
Date:   Tue Aug 26 19:48:51 2008 +0800

    test for current head

I read a few similar questions on stack overflow like Pass an argument to a Git alias command but have not still not been able to figure this out.

The best I could come up with was to modify my .gitconfig file as follows:

[alias]
    last = log -1 HEAD
    mylast = "!sh -c 'echo /usr/local/bin/git last -$0 HEAD'"

Then if I run this at the command line:

$ git mylast 12

I get this:

/usr/local/bin/git last -12 HEAD

That actually looks right. But if I remove the echo in front, it just hangs like it is waiting for input. I tried switching $0 for $1 but that didn't seem to help either.

What am I doing wrong?

Also, is there a way to set it up so that if I just type git last with no number then it would default to "1" ?

Community
  • 1
  • 1
cwd
  • 53,018
  • 53
  • 161
  • 198

1 Answers1

3
last = !sh -c 'git log "-${1:-1}" HEAD' -

This takes advantage of the shell parameter interpolation default syntax, ${var:-default} which substitutes default if the variable var is not set.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • nice! any way to get it set to 1 by default if no parameter is specified? – cwd Mar 05 '12 at 04:13
  • Sure. Change it from `$1` to `${1:-1}`. – Amber Mar 05 '12 at 04:15
  • 1
    (Also if you wanted, you could change the `HEAD` to `${2:-HEAD}` which would give you the ability to request `git last 2 ` for an arbitrary branch.) – Amber Mar 05 '12 at 04:18
  • 1
    This is an excellent little alias, to do this on oneline (and avoid adding it to .gitconfig directly) the following works from a bash shell: `set +H` then `git config --global alias.last "!sh -c 'git log -\${1:-1} \${2:-HEAD}' -"`. Shell needs the exclamation mark and the dollars escaped. – Mark Fisher Mar 05 '12 at 12:06