2

基本上我想输入show并检查是否show定义了命令或别名并触发它并且未定义触发git show

例如rm应该做rmcheckout应该做git checkout

是否可以在其中编程bashrc

4

5 回答 5

4

这非常容易:

master tmp$ trap 'git $BASH_COMMAND' ERR
master tmp$ touch foo
master tmp$ rm foo
master tmp$ add foo
bash: add: command not found
fatal: pathspec 'tmp/foo' did not match any files
master tmp$ branch
bash: branch: command not found
  aix
  allocators
  ...

这运行通常的touchrm命令,但是因为没有add命令它运行git add foo并且因为没有branch命令它运行git branch

The trap command is run on any error, so not only when a command isn't found. You would probably want to do something smarter e.g. run a script which checks whether $? is 127 (the code bash sets when a command is not found) and then checks if running it with git instead would work (e.g. by checking for a command called git-xxx where xxx is the first word of $BASH_COMMAND). I leave that as an exercise for the reader.

于 2012-10-09T00:34:06.103 回答
2

There's no simple and proper way to achieve what you need. I think the best to do is to make an alias in ~/.bashrc for every git commands.

But on many distros, if you check man git, there's some Main porcelain commands that looks like aliases.

You can list all of them using

PAGER= man git | grep -oP 'git-\w+(?=\()'
于 2012-10-09T00:46:50.893 回答
2

When bash cannot find a command, it calls command_not_found_handle (if defined). You can define it to look something like this:

command_not_found_handle () {
    git "$@" || { echo "$1 not a 'git' command either"; exit 127; }
}
于 2012-10-09T13:01:12.313 回答
0

添加到您的~/.bashrc

alias show='git show'
alias checkout='git checkout'
...

注意不要为已经执行其他操作的命令创建别名。这可能会破坏其他程序。

于 2012-10-09T00:29:00.540 回答
0

Here's one way of getting a list of all your git commands:

git help -a | egrep '^  [a-zA-Z0-9]' | xargs -n1 | sed 's/--.*//' | sort -u

Or you could use what's in contrib/completion/git-completion.sh: (This is probably better since you'll probably be looping anyway. Note: You'll need to consider for duplicates, but they don't really matter for alias)

__git_list_all_commands ()
{
    local i IFS=" "$'\n'
    for i in $(git help -a|egrep '^  [a-zA-Z0-9]')
    do
        case $i in
        *--*)             : helper pattern;;
        *) echo $i;;
        esac
    done
}
于 2012-10-09T01:19:12.277 回答