This answer教了如何在git别名中执行自定义bash命令,而本文(One weird trick for powerful Git aliases)教的很漂亮。但是,当我为内部git命令加上别名时,它似乎不起作用。如何用自定义脚本替换内部git命令?
例如:我有一个自定义的python脚本: custom_script.py
print("hello")
在我的project_name/.git/config
文件中,添加以下别名:
[alias]
statuss = "!f() { \
python3 custom_script.py && git status; \
}; f"
然后我运行git statuss
,它运行良好!我看到打印出“ hello”,然后显示“ git status”返回消息。
但是,如果我将别名从statuss
重命名为status
,它将不再起作用。
[alias]
status = "!f() { \
python3 custom_script.py && git status; \
}; f"
我该如何做,以便只需调用git status
,它首先 调用我的“ custom_script.py”,然后然后运行{{ 1}}?
注意:
答案 0 :(得分:1)
Git doesn't allow you to override internal commands in aliases, because doing so would break any scripting that uses those internal commands that expected them to function as normal. This is especially important because some Git commands are shell scripts, and overriding those commands could break Git's shell scripts.
You can override this by writing a shell script called git
which you place into a directory in $PATH
, and that is the easiest way to accomplish it. However, be aware that the first argument to git
need not be a command: git
takes a large number of options which precede the command, such as -c
and -C
, and your script would need to parse those in order to avoid breaking any other scripts that might call git
(which might, for example, include your editor).
So while this is possible, it's very tricky, and any correct solution would be fairly lengthy (which is why I haven't attempted it here). Generally, the recommended solution is to use an alias which doesn't mirror a builtin name, which is much simpler.
However, if you want this only for interactive use, it's possible to create a script in your $PATH
called, say, git-wrapper
, and do something like this inside:
#!/bin/sh
if [ "$1" = status ]
then
python3 custom_script.py
fi
exec git "$@"
You can then run alias git=git-wrapper
in your ~/.bash_profile
or ~/.zshrc
(but not ~/.bashrc
or ~/.zshenv
). This will affect only cases where you specifically write git status
, but not any scripting uses. This might be good enough for you, or not.
答案 1 :(得分:0)
您可以使用以下命令:git config --global alias.co checkout就是这样。