Skip to content

Instantly share code, notes, and snippets.

@samirkape
Created March 8, 2021 03:50
Show Gist options
  • Save samirkape/07b1fc218592bd95b405851c1ce28a33 to your computer and use it in GitHub Desktop.
Save samirkape/07b1fc218592bd95b405851c1ce28a33 to your computer and use it in GitHub Desktop.
Accidental git reset --hard : Future damage control
function grh()
{
#Pass any arbitary argument to this command ( e.g. grh 1 ) to skip backup
if [ "$1" ]
then
echo "Skip backup? (y/n): "
read answer
if [ "$answer" != "${answer#[Yy]}" ] ;then
echo "Run: git reset --hard without creating backup"
git reset --hard
return
fi
fi
#Setup backup dir name
name=`date +"%I:%M:%S"`
date=`date +"%d-%m-%y"`
dir="/home/"$USER"/Desktop/store/$date/$name"
mkdir -p $dir
#Store git diff result for reference
echo "Generate: git diff results.."
git diff --color . > $dir/git.diff
#Copy only changed files
echo "Copy: only changed files.."
zip -r $dir/src.zip `git diff --relative --name-only .`
#Check if copy was successful
if [ $? -ne 0 ]
then
echo " "
echo "Copy: Failed.."
echo "Copy: Aborting git reset --hard"
return
else
#Run git reset --hard
echo "Backup created at $dir"
echo "Run: git reset --hard"
git reset --hard
fi
}
@samirkape
Copy link
Author

samirkape commented Mar 8, 2021

Running a grh command

Creates a backup

  1. Changed files
  2. Colored git diff result for reference

Where?
/home/user/Desktop/.store/Date/Time/src.zip

Additional Options
Provide input argument to the command in order to skip the backup process
grh 1


Usage

Step 1 -
Save this file in your home directory and name it .gitreset

Step 2 -
Open ~/.bashrc and add below line at the end.
source ~/.gitreset

Step 3 -
Use the grh abbreviation in place of git reset --hard

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment