Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a custom git/bash script?

Tags:

git

git-bash

awk

I'd like to make it so that if I type git recent in my terminal, it actually runs: git reflog | egrep -io "moving from ([^[:space:]]+)" | awk '{ print $3 }' | awk ' !x[$0]++' | egrep -v '^[a-f0-9]{40}$' | head -n5 giving me the 5 most recent git branches I've checked out to.

Bonus points: I'd like to add an argument, so that if I type git recent 20 it runs: git reflog | egrep -io "moving from ([^[:space:]]+)" | awk '{ print $3 }' | awk ' !x[$0]++' | egrep -v '^[a-f0-9]{40}$' | head -n20 giving me the 20 most recent git branches I've checked out to.

Also, any readings/tutorials series to recommend in to better understand how this script works, and how to write custom bash scripts? Thanks.

like image 245
gnarois Avatar asked Oct 30 '25 21:10

gnarois


2 Answers

If you create a script, accessible from your path, and name it : git-foo, then :

git foo arg1 arg2 ...

will invoke that script, with arguments.

It's the advised way if fitting your command on one single line for a git alias becomes too complicated.

like image 98
LeGEC Avatar answered Nov 03 '25 09:11

LeGEC


are you aware of git aliases ?

Permanent aliases are stored in your .gitconfig file, usually in your home directory.

You can edit this file and append:

[alias]
    recent = "!git reflog | egrep -io 'moving from ([^[:space:]]+)' | awk '{ print $3 }' | awk ' !x[$0]++' | egrep -v '^[a-f0-9]{40}$' | head -n5"

You would use it like so git recent


What does ! mean ?

As you may have noticed the !. I will explain what's what. A standard alias such as: cm = commit -m will when used go from git cm to git commit -m.

But as a matter of fact you can tell git to replace the whole line. If I were to write cm = !commit -m when used the command would go from git cm to commit -m

That's what the ! does.


Bonus point

It is way more ugly but still worth checking:

[alias] 
    bonus = "!f() { \
             git reflog | egrep -io 'moving from ([^[:space:]]+)' | awk '{ print $3 }' | awk ' !x[$0]++' | egrep -v '^[a-f0-9]{40}$' | head -n$1; \
             }; f"

You would use it like so git bonus <number of branches>

like image 41
Paulo Avatar answered Nov 03 '25 10:11

Paulo