Skip to content

Instantly share code, notes, and snippets.

@gbili
Created February 25, 2024 14:43
Show Gist options
  • Save gbili/eb9f0d64d1ff4528033992aecf0c67db to your computer and use it in GitHub Desktop.
Save gbili/eb9f0d64d1ff4528033992aecf0c67db to your computer and use it in GitHub Desktop.
Prevent unintended git reset --hard
#!/bin/bash
# alias this script in your shell configuration file (e.g., .bashrc, .zshrc) with something like alias git='./git-reset-safe.sh', but ensure the script is in your PATH or use the full path to the script in the alias.
# Check if the first argument is 'reset' and the second is '--hard'
if [ "$1" = "reset" ] && [ "$2" = "--hard" ]; then
current_dir=$(pwd)
echo "🚨 About to nuke changes in: $current_dir"
echo "Paste the directory path to prove you're serious (no take-backs!):"
read user_input
if [ "$user_input" = "$current_dir" ]; then
git "$@"
echo "💥 Boom! Changes gone. Hope you meant that!"
else
echo "🛑 Nope, that didn't match. Crisis averted!"
fi
else
git "$@"
fi
@gbili
Copy link
Author

gbili commented Feb 25, 2024

  1. Open your terminal.
  2. Use a text editor to create the script file:
    nano git-reset-safe.sh
  3. Copy and paste the script provided into the editor.
  4. Save and exit the editor (in nano, press Ctrl+O, Enter, and then Ctrl+X).
  5. Make the script executable:
    chmod +x git-reset-safe.sh
  6. Move the script to a directory in your PATH to use it globally (optional):
    sudo mv git-reset-safe.sh /usr/local/bin/
  7. Add an alias in your shell configuration file (.bashrc, .zshrc, etc.):
    echo "alias git='git-reset-safe.sh'" >> ~/.bashrc
    (Adjust .bashrc to your shell’s configuration file as necessary.)
  8. Reload your shell configuration:
    source ~/.bashrc

Now, when you use git reset --hard, it will be intercepted by your git-reset-safe.sh script, requiring confirmation before proceeding.

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