Skip to content

Instantly share code, notes, and snippets.

@twinbird
Created May 1, 2022 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twinbird/77df39272f58489a5c525ce4a579291d to your computer and use it in GitHub Desktop.
Save twinbird/77df39272f58489a5c525ce4a579291d to your computer and use it in GitHub Desktop.
#!/bin/bash
# nco.sh
# checkout next/prev commit on current git repository
# Usage:
# nco [next|prev]
# use only on detached HEAD branch
if [[ ! -e .git ]]; then
echo "$PWD is not git repository."
exit 1
fi
current_branch_name=`git branch | cut -d " " -f 2`
if [[ $current_branch_name != "(HEAD" ]]; then
echo "current branch is not detached branch"
exit 1
fi
current=`git log --oneline | awk '{print $1}' | head -n 1`
git checkout main > /dev/null 2>&1
next=`git log --oneline | awk '{print $1}' | grep -B1 $current | head -n1`
prev=`git log --oneline | awk '{print $1}' | grep -A1 $current | tail -n1`
if [[ "$1" = "next" && $next = $current ]]; then
git checkout $current > /dev/null 2>&1
echo "this commit is latest commit"
exit 1
fi
if [[ "$1" = "prev" && $prev = $current ]]; then
git checkout $current > /dev/null 2>&1
echo "this commit is first commit"
exit 1
fi
if [[ "$1" = "next" || "$1" = "" ]]; then
git checkout $next > /dev/null 2>&1
else
git checkout $prev > /dev/null 2>&1
fi
git log --oneline | head -n 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment