Adding Custom Commands in Git

From Qiki
Jump to navigation Jump to search

Adding Custom Commands in Git

Git is flexible and allows you to extend its functionality. You can add your own custom commands in two main ways: aliases and custom scripts.



1. Git Aliases

Aliases are shortcuts that let you run common Git commands faster or create combinations of options.

Example: Simple Alias

git config --global alias.co checkout

Now, instead of typing:

git checkout branch-name

you can type:

git co branch-name

Example: Complex Alias

git config --global alias.hist "log --oneline --graph --decorate --all"

This creates a git hist command that shows a visual log of commits.



2. Git Custom Scripts

If you want a brand new Git command, you can create a script. Git will recognize any executable script in your PATH with the format git-<command> as a new command.

Steps to Create a Custom Command

  1. Create a script

    touch ~/bin/git-hello
    
  2. Add content

    #!/bin/bash
    echo "Hello from custom git command!"
    
  3. Make it executable

    chmod +x ~/bin/git-hello
    
  4. Ensure ~/bin is in your PATH

Now you can run:

git hello

And see:

Hello from custom git command!

3. Advanced Example

You can create scripts that interact directly with Git.

Undo Last Commit (but keep changes staged)

#!/bin/bash
# Save this as git-uncommit

git reset --soft HEAD~1

Usage:

git uncommit

This will remove the last commit while keeping your changes staged.



Summary

  • Aliases: Best for shortcuts and simple combinations of Git commands.
  • Scripts: Best for creating completely new commands.

By using both methods, you can make Git work exactly the way you want.