Skip to content

Git - 推送操作

在将更改提交(commit)到本地仓库后,使用 git push 命令可以将这些本地提交上传到远程仓库(remote repository)。这使得你的更改可以被其他协作者访问,并作为备份。例如,Jerry 已经进行了一些提交,并且可能使用 git commit --amend 修改了他的最后一次提交。

他首先执行 git log 命令来查看他本地 main 分支上的最新提交详情:

[jerry@devbox project]$ git log -1

上述命令将产生类似如下的输出:

commit d1e19d316224cddc437e3ed34ec3c931ad803958 (HEAD -> main)
Author: Jerry Mouse <jerry@example.com>
Date: Tue Jan 16 09:15:00 2024 +0000
Refactor my_strlen to use size_t and const pointer

在推送(push)之前,最好先检查将要推送的更改。他可以使用 git show 命令加上提交 ID(或者使用 HEAD 代表最新的提交)来查看提交详情和实际的更改(diff):

[jerry@devbox project]$ git show HEAD

上述命令将产生显示提交信息和 diff 的输出:

commit d1e19d316224cddc437e3ed34ec3c931ad803958 (HEAD -> main)
Author: Jerry Mouse <jerry@example.com>
Date: Tue Jan 16 09:15:00 2024 +0000
Refactor my_strlen to use size_t and const pointer
diff --git a/string_utils.c b/string_utils.c
index 7da2992..0000000 100644
--- a/string_utils.c
+++ b/string_utils.c
@@ -1,15 +1,15 @@
#include <stdio.h>
-int my_strlen(char *s) // Old version
+size_t my_strlen(const char *s) // 旧版本
{
- char *p = s;
+ const char *p = s;
while (*p)
++p;
return (p - s);
}
int main(void)
{
int i;
char *s[] =
{
"Git tutorials",
"Tutorials Point"
};
for (i = 0; i < 2; ++i)
- printf("string length of %s = %d\n", s[i], my_strlen(s[i])); // Old printf
+ printf("string length of \"%s\" = %zu\n", s[i], my_strlen(s[i])); // 使用 %zu 的新 printf
return 0;
}

Jerry 对他的更改很满意,准备将它们推送到 origin 远程仓库的 main 分支上。

[jerry@devbox project]$ git push origin main

上述命令将产生类似如下的输出:

Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to X threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 517 bytes | 517.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0), pack-reused 0
To https://git.example.com/our_team/project.git
abc1234..d1e19d3 main -> main

Jerry 的更改已成功推送到远程仓库。现在,其他开发者可以 fetch 或 pull 这些更改来更新他们的本地副本。如果远程分支有 Jerry 没有的更改,推送可能会被拒绝(需要先执行 git pull),正如在 ‘Git - 更新操作’ 章节中看到的那样。