简体   繁体   English

如何使用一个.gitconfig别名调用多个git命令

[英]How to call multiple git commands using one .gitconfig alias

Here are my current aliases in .gitconfig, and they work great. 这是我目前在.gitconfig中的别名,它们工作得很好。 However, I'd like to have a single alias that can do all three. 但是,我希望有一个别名可以同时使用这三个别名。

Example of what I'd like at terminal: 我想要的终端示例:

git x my_commit_message

Psuedo-code of .gitconfig: .gitconfig的伪代码:

[alias]
         x = add -A <then do> commit -m <use variable from command line> push

I have push set to default = current, so push alone works. 我已将push设置为default = current,所以单独使用push即可。

[push]
    default = current

Any help is appreciated, thanks! 任何帮助表示赞赏,谢谢!

If you want to combine add, commit and push, you'll need a bash function. 如果要组合添加,提交和推送,则需要一个bash函数。 Git add and commit can be combined with git -am "msg" , but the push can only be done as an additional command. 可以将git add和commit与git -am "msg"结合使用,但是只能作为附加命令来完成推送。 So, just define a bash function like this: 因此,只需定义一个bash函数,如下所示:

gacp() {
  git add -A &&
  git commit -m "${1?'Missing commit message'}" &&
  git push
}

This works by doing the git add -A first, and if it succeeds, then the command git commit -m is executed, with the required message, and if that succeeds, then the git push is executed. 这是通过首先执行git add -A如果成功,则执行git commit -m命令,并带有所需的消息, 如果成功,则执行git push

It's important to make the latter commands depend on successful execution of the previous commands in order to avoid downstream messes. 重要的是,使后一个命令依赖于前一个命令的成功执行,以避免下游混乱。 In other words, you don't really want to commit changes unless the add succeeded, and you don't really want to push your most recent commits unless the commit succeeded. 换句话说,除非add成功,否则您实际上并不想commit更改,并且除非commit成功,否则您就不想推送最新的commit

You use it like this: 您可以这样使用它:

gacp "Latest changes"

You need to use shell function to be able to execute multiple commands inside a git alias. 您需要使用shell函数才能在git别名内执行多个命令。

  1. First, start with ! 首先,从开始! so Git will run it as a shell command. 因此Git会将其作为shell命令运行。
  2. Write your function, like: f() { git add -A && git commit -m "$1" && git push } . 编写函数,例如: f() { git add -A && git commit -m "$1" && git push }
  3. Execute your function just after its declaration. 声明后立即执行功能。

You should write something like: 您应该编写如下内容:

[alias]
        x = "!f() { git add -A && git commit -m \"$1\" && git push } f"

Note that: 注意:

  • $1 will be replaced by your variable from command line, $1将由命令行中的变量替换,
  • && will execute the next command only if the previous one has succeed. &&仅在上一个命令成功执行后才执行下一个命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM