Skip to content

Instantly share code, notes, and snippets.

@PillTime
Last active November 13, 2025 19:57
Show Gist options
  • Select an option

  • Save PillTime/fc375f272292f35a71d15f1fde5b9646 to your computer and use it in GitHub Desktop.

Select an option

Save PillTime/fc375f272292f35a71d15f1fde5b9646 to your computer and use it in GitHub Desktop.
go forwards or backwards in git history
#!/usr/bin/env sh
set -eu
print_usage() {
printf 'Usage: %s <prev|next>\n' "${0}"
printf '\tprev: move to the previous commit\n'
printf '\tnext: move to the next commit\n'
}
if [ "${#}" -ne 1 ]; then
print_usage
exit 1
fi
case "${1}" in
'prev')
current="$(git rev-parse HEAD)"
history="$(git rev-list --children --all)"
line="$(echo "${history}" | grep -Em 1 "\w\s${current}$" || true)"
if [ "${line}" = '' ]; then
printf 'Already at the first commit.\n'
exit 1
fi
prev="$(echo "${line}" | cut -d ' ' -f 1)"
git checkout "${prev}"
;;
'next')
current="$(git rev-parse HEAD)"
history="$(git rev-list --children --all)"
line="$(echo "${history}" | grep -E "^${current}")"
next="$(echo "${line}" | cut -d ' ' -f 2)"
if [ "${next}" = "${current}" ]; then
printf 'Already at the last commit.\n'
exit 1
fi
git checkout "${next}"
;;
*)
printf 'Unknown command: %s.\n' "${1}"
print_usage
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment