Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define an alias for a Git subcommand (e.g. for `list` in `git stash list`)?

Whenever I try to type git stash list my fingers go rogue and type git stash ls. I'd really like to alias ls to list, but only within the stash subcommand. Is this possible with git aliases?

like image 678
valadil Avatar asked Mar 30 '15 13:03

valadil


People also ask

How do I make an alias command in git?

It is important to note that there is no direct git alias command. Aliases are created through the use of the git config command and the Git configuration files. As with other configuration values, aliases can be created in a local or global scope.

Where do I put git alias?

Your git aliases are often stored per your user's configuration at ~/. gitconfig . You can also manually set aliases using, for example, the command git config alias. s 'status -s' .

How can add a git URL as an alias?

Add git alias The simplest way to add a git alias is by running a command to add the alias to the git global configuration file. For example, running the command git config --global alias. hist "log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short" will add the alias git hist .

What command would create the My alias for the commit command?

To create this alias, just run this command: git config --global alias.


1 Answers

Git doesn't offer any mechanism for aliasing a subcommand; see the git-config man page.

However, there is a trick for achieving the same effect: use a small wrapper around the git binary by defining a shell command also called git that does what you want:

git() {
    if [ "$1" = "stash" -a "$2" = "ls" ]
    then
        command git stash list
    else
        command git $@
    fi;
}

Not pretty, but does the job (as tested in one of my repositories):

# starting from a dirty working state...
$ git stash save
Saved working directory and index state WIP on master: 7c6655d add missing word in documentation
HEAD is now at 7c6655d add missing word in documentation
$ git stash ls
stash@{0}: WIP on master: 7c6655d add missing word in documentation

Note that this approach isn't very robust. In particular, git stash list will not be run if there are other command-line arguments between git and stash ls, as in

git -C ~/Desktop stash ls

The approach should be sufficient for your use case, though.

To avoid having to retype the definition of that git function every time you start your shell, you should put it in one of the files that your shell is configured to source.

like image 57
jub0bs Avatar answered Oct 13 '22 00:10

jub0bs