git: check when the last fetch was run

git: check when the last fetch was run

I have a script that shows the last few log changes, but if a fetch hasn’t been ran in a day or two, I want the script to run it manually.

Here’s sample bash code of how it would work:

#!/bin/bash

# this is what I need:
last_fetch_date=`git fetch --show-last-fetch-date`

# do the math to see how long ago
timestamp=`date -d "$last_fetch_date" +%s`
now=`date +%s`
diff=`echo $now - $timestamp | bc -l`

# two days
if [ `echo $diff' >= 2*24*60*60' | bc -l` == "1" ]; then
    git fetch --tags
fi

There is no way to know when the last git fetch was run, as git does not store that information. If you want to know, you will have to write a time stamp somewhere every time you run it.

However, you can find out when git fetch last actually fetched something. Every time git fetch fetches new commits, it updates the reflog. To see it, use e.g.

git reflog show --date=iso -n 1 origin/master

This will show the last change to origin/master, with the date. Caveat: This will also show when
you modified it (by pushing).

Finally, it is probably easier to just fetch whenever it’s convenient, without all this checking. git fetch runs very quickly if there’s nothing to fetch.

Here’s what I ended up doing, thanks to @sleske

#!/bin/bash

# do the math to see how long ago was the last fetch
 now=`date +%s`
 last_fetch=`git reflog show --date=raw -n 1 origin/master | grep -oE '{[0-9]+' | sed 's%{%%'`
 diff=`echo $now - $last_fetch | bc -l`
if [ `echo $diff' >= 2*24*60*60' | bc -l` == "1" ]; then
    git fetch -q
    git fetch --tags -q
fi
.
.
.
.