Skip to content

Instantly share code, notes, and snippets.

@Cliabhach
Last active January 16, 2019 18:40
Show Gist options
  • Select an option

  • Save Cliabhach/303378c2f9233786a21864f09b43e821 to your computer and use it in GitHub Desktop.

Select an option

Save Cliabhach/303378c2f9233786a21864f09b43e821 to your computer and use it in GitHub Desktop.
Git log, with date range
#!/bin/bash
###
# Licensed under CC-BY-SA 4.0 by Philip Cohn-Cort
#
# Feel free to comment here on the GitHub Gist if you have feedback or
# want to use this. I wrote it up to sort of refresh my knowledge of
# Awk and Git formatting, so I wouldn't exactly recommend this for
# production usage as is.
#
# Tested with Bash 4.4.19, GNU Coreutils (fold & sort & tr) 8.28, Git 2.20.1, Gawk 4.1.4
#
# References:
#
# Git log colors: https://stackoverflow.com/q/5889878
# Basic awk syntax: GAWK(1) manual
# Basic awk debugging: https://unix.stackexchange.com/q/72799
# Detecting date ranges: https://stackoverflow.com/a/37311841
# Wrapping long text: https://unix.stackexchange.com/a/25174
# Sorting on fields: SORT(1) manual and https://stackoverflow.com/a/17048248
#
start_date=$1
end_date=$2
DATE_COLOR='\033[0;31m'
COLORLESS='\033[0m'
if [ $# -eq 2 ]
then
printf "Checking date range ${DATE_COLOR}$start_date${COLORLESS} to ${DATE_COLOR}$end_date${COLORLESS}...."
echo
echo
else
fold -w 80 -s <<EOF
Git Log-range command (unofficial)
Sorry, you need to provide two arguments to '$0': the day immediately before these commits were authored, and the day immediately after.
Any substring of git's ISO 8601 format ('date time', like '2018-01-16 10:20:30') is acceptable.
EOF
exit 1
fi
###
# Check that field 3 is between start and end date, using alphabetic comparison
#
# Be careful with color codes - if any are right next to the date string printed
# by the git log command run at the end of the script, this
# comparison might unilaterally fail
awk_command="\$3 >= \"$start_date\" && \$3 <= \"$end_date\""
# You can redefine the awk command here to verify that fields are shown correctly
#awk_command='{print $1 , $3 , $5}'
###
# Git log with
# ...--color=always to get colored output (--color=auto strips colors before the first pipe)
# ...--date=iso for consistent and predictable date format
# ...--pretty=format to control precisely what is shown for each commit
# piped into awk to find only certain dates
# piped into sort with
# ...-k4 to sort on fields numbered 3 and 4 (which are the date and time)
# piped into tr to replace pipes with newlines
git log --color=always --date=iso --pretty=format:'%C(auto)commit %H%Creset|%Cred %ad%x08 %aN%Creset||%s|' | awk "$awk_command" | sort -k3,4 | tr '|' '\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment