Git使用教程:轻松掌握版本控制利器,提升开发效率!-(1)git的基本命令讲解

目录

1. 背景

2. git简介

3. git常用指令

        3.1 clone

        3.2 checkout

        3.3 branch

        3.4 add

        3.5 commit

        3.6 push

        3.7 pull

4. 结语


1. 背景

  • 工具名称:git
  • 应用场景:git最主要的应用场景是用于管理和控制代码的版本。开发人员可以使用Git来跟踪代码的变化,记录每次的提交,并轻松地回滚到之前的版本。git还提供了分支管理功能,可以方便地创建、切换和合并分支,使得团队成员可以并行开发不同的功能或修复bug。
  • 与其他版本控制系统的区别:与集中式版本控制系统(如SVN)相比,Git具有更高的性能、更强大的分支管理和更好的代码合并能力。

本文将对git的几个基本操作进行详细讲解,帮助大家从零开始学习git的用法。

2. git简介

   git简单来说就是代码版本控制系统,通过他可以进行多人开发同一个项目然后讲每个人的代码块合并完成一个大项目,还能控制代码版本记录等。官方文档:https://git-scm.com/docs

git四个区域:

  1. 工作区:处理工作的区域(即做项目打代码的区域)。

  2. 暂存区:已完成的工作临时存放区域,等待被提交。

  3. 本地仓库:存放数据的地方,但是还在本机上,若电脑存储空间损坏还是会造成代码消失。

  4. Git远程仓库:最终的存放区域,即远程服务器,电脑存储空间损坏也不影响远程仓库数据。

git四个状态:

  1. 未跟踪(Untracked):文件没有加入到git库中,不参与版本控制,使用git add变为暂存。

  2. 已暂存(Staged):表示对已修改文件的当前版本做了标记,使之包含在下次提交的列表。

  3. 已修改(Modified):表示修改了文件,但还没将修改的结果放到暂存区。

  4. 已提交(Unmodified):表示文件已经安全地保存在本地Git仓库。

    3. git常用指令

    3.1 clone

    git clone [--template=<template-directory>]
    	  [-l] [-s] [--no-hardlinks] [-q] [-n] [--bare] [--mirror]
    	  [-o <name>] [-b <name>] [-u <upload-pack>] [--reference <repository>]
    	  [--dissociate] [--separate-git-dir <git-dir>]
    	  [--depth <depth>] [--[no-]single-branch] [--no-tags]
    	  [--recurse-submodules[=<pathspec>]] [--[no-]shallow-submodules]
    	  [--[no-]remote-submodules] [--jobs <n>] [--sparse] [--[no-]reject-shallow]
    	  [--filter=<filter> [--also-filter-submodules]] [--] <repository>
    	  [<directory>]

    官网原文:

    Clones a repository into a newly created directory, creates remote-tracking branches for each branch in the cloned repository (visible using git branch --remotes), and creates and checks out an initial branch that is forked from the cloned repository’s currently active branch.

    After the clone, a plain git fetch without arguments will update all the remote-tracking branches, and a git pull without arguments will in addition merge the remote master branch into the current master branch, if any (this is untrue when "--single-branch" is given; see below).

    This default configuration is achieved by creating references to the remote branch heads under refs/remotes/origin and by initializing remote.origin.url and remote.origin.fetch configuration variables.

    中文翻译:

    将仓库克隆到一个新创建的目录中,为克隆仓库中的每个分支创建远程跟踪分支(可以使用git branch --remotes查看),并创建并切换到一个从克隆仓库当前活动分支分叉出来的初始分支。 克隆完成后,执行简单的git fetch命令(不带参数)将更新所有远程跟踪分支,而执行git pull命令(不带参数)将额外将远程主分支合并到当前主分支中(除非使用了"--single-branch"选项;详见下文)。 这个默认配置是通过在refs/remotes/origin下创建对远程分支头的引用,并初始化remote.origin.url和remote.origin.fetch配置变量来实现的。

    例程说明:将特定仓库里面的所有文件复制到本地,以github为例,我们首先在github上面找到一个想要的工程的链接,然后在界面上获取到工程的ssh地址

    git@github.com:FreeRTOS/FreeRTOS-Kernel.git

 在powershell中输入如下指令

git clone git@github.com:FreeRTOS/FreeRTOS-Kernel.git
cd .\FreeRTOS-Kernel\
ls

 运行结果

PS D:\> git clone git@github.com:FreeRTOS/FreeRTOS-Kernel.git
Cloning into 'FreeRTOS-Kernel'...
remote: Enumerating objects: 173717, done.
remote: Counting objects: 100% (1435/1435), done.
remote: Compressing objects: 100% (682/682), done.
remote: Total 173717 (delta 809), reused 1224 (delta 669), pack-reused 172282
Receiving objects: 100% (173717/173717), 115.61 MiB | 65.00 KiB/s, done.

Resolving deltas: 100% (124658/124658), done.
PS D:\> cd .\FreeRTOS-Kernel\
PS D:\FreeRTOS-Kernel> ls


    目录: D:\FreeRTOS-Kernel


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----          2024/4/2     15:56                .github
d-----          2024/4/2     15:56                examples
d-----          2024/4/2     15:56                include
d-----          2024/4/2     15:56                portable
-a----          2024/4/2     15:56            353 .git-blame-ignore-revs
-a----          2024/4/2     15:56             15 .gitattributes
-a----          2024/4/2     15:56            396 .gitmodules
-a----          2024/4/2     15:56          20038 CMakeLists.txt
-a----          2024/4/2     15:56          17807 croutine.c
-a----          2024/4/2     15:56            691 cspell.config.yaml
-a----          2024/4/2     15:56          36597 event_groups.c
-a----          2024/4/2     15:56            155 GitHub-FreeRTOS-Kernel-Home.url
-a----          2024/4/2     15:56         169900 History.txt
-a----          2024/4/2     15:56           1055 LICENSE.md
-a----          2024/4/2     15:56          10221 list.c
-a----          2024/4/2     15:56             96 manifest.yml
-a----          2024/4/2     15:56           4869 MISRA.md
-a----          2024/4/2     15:56         130682 queue.c
-a----          2024/4/2     15:56            145 Quick_Start_Guide.url
-a----          2024/4/2     15:56           7210 README.md
-a----          2024/4/2     15:56          72373 stream_buffer.c
-a----          2024/4/2     15:56         359564 tasks.c
-a----          2024/4/2     15:56          57909 timers.c


PS D:\FreeRTOS-Kernel>

3.2 checkout

git checkout [-q] [-f] [-m] [<branch>]
git checkout [-q] [-f] [-m] --detach [<branch>]
git checkout [-q] [-f] [-m] [--detach] <commit>
git checkout [-q] [-f] [-m] [[-b|-B|--orphan] <new-branch>] [<start-point>]
git checkout [-f] <tree-ish> [--] <pathspec>…​
git checkout [-f] <tree-ish> --pathspec-from-file=<file> [--pathspec-file-nul]
git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [--] <pathspec>…​
git checkout [-f|--ours|--theirs|-m|--conflict=<style>] --pathspec-from-file=<file> [--pathspec-file-nul]
git checkout (-p|--patch) [<tree-ish>] [--] [<pathspec>…​]

官网原文:

Updates files in the working tree to match the version in the index or the specified tree. If no pathspec was given, git checkout will also update HEAD to set the specified branch as the current branch.

中文翻译:

将工作树中的文件更新为与索引或指定的树版本相匹配。如果没有指定路径规范(pathspec),git checkout命令还会将HEAD更新为将指定分支设置为当前分支。

例程说明:切换分支或恢复已被修改的文件

在刚才的界面上,点击分支的图标,选择一个已有分支 smp,然后在powershell执行以下命令

git checkout smp
git branch

运行结果

PS D:\FreeRTOS-Kernel> git checkout smp
Switched to a new branch 'smp'
branch 'smp' set up to track 'origin/smp'.
PS D:\FreeRTOS-Kernel> git branch
  main
* smp
PS D:\FreeRTOS-Kernel>

下面我们可以创建一个属于自己的开发分支

git checkout -b dev/my_branch
git branch

 运行结果

PS D:\FreeRTOS-Kernel> git checkout -b dev/my_branch
Switched to a new branch 'dev/my_branch'
PS D:\FreeRTOS-Kernel> git branch
* dev/my_branch
  main
  smp
PS D:\FreeRTOS-Kernel>

3.3 branch

git branch [--color[=<when>] | --no-color] [--show-current]
	[-v [--abbrev=<n> | --no-abbrev]]
	[--column[=<options>] | --no-column] [--sort=<key>]
	[--merged [<commit>]] [--no-merged [<commit>]]
	[--contains [<commit>]] [--no-contains [<commit>]]
	[--points-at <object>] [--format=<format>]
	[(-r | --remotes) | (-a | --all)]
	[--list] [<pattern>…​]
git branch [--track[=(direct|inherit)] | --no-track] [-f]
	[--recurse-submodules] <branchname> [<start-point>]
git branch (--set-upstream-to=<upstream> | -u <upstream>) [<branchname>]
git branch --unset-upstream [<branchname>]
git branch (-m | -M) [<oldbranch>] <newbranch>
git branch (-c | -C) [<oldbranch>] <newbranch>
git branch (-d | -D) [-r] <branchname>…​
git branch --edit-description [<branchname>]

官网原文:

If --list is given, or if there are no non-option arguments, existing branches are listed; the current branch will be highlighted in green and marked with an asterisk. Any branches checked out in linked worktrees will be highlighted in cyan and marked with a plus sign. Option -r causes the remote-tracking branches to be listed, and option -a shows both local and remote branches.

With a -d or -D option, <branchname> will be deleted. You may specify more than one branch for deletion. If the branch currently has a reflog then the reflog will also be deleted.

Use -r together with -d to delete remote-tracking branches. Note, that it only makes sense to delete remote-tracking branches if they no longer exist in the remote repository or if git fetch was configured not to fetch them again.

中文翻译:

如果使用--list选项,或者没有非选项参数,将列出现有的分支;当前分支将以绿色高亮显示,并带有一个星号。在链接的工作树中检出的分支将以青色高亮显示,并带有一个加号。选项-r将列出远程跟踪分支,选项-a显示本地和远程分支。

使用-d或-D选项,<branchname>将被删除。可以指定多个要删除的分支。如果分支当前具有reflog,则还将删除reflog。

使用-r和-d选项一起删除远程跟踪分支。请注意,只有在远程仓库中不再存在这些分支,或者如果配置了git fetch不再获取它们时,才有意义删除远程跟踪分支。

例程说明:在前面的操作中一直使用到的git branch指令,就是用来列举、创建和删除分支。前面已经用git checkout -b的指令创建了分支,下面我们将试一下删除指令,要注意的是,我们删除分支前,需要先checkout到其他分支。

 在powershell中输入如下指令

git branch
git checkout main
git branch -D dev/my_branch
git branch

运行结果

PS D:\FreeRTOS-Kernel> git branch
* dev/my_branch
  main
  smp
PS D:\FreeRTOS-Kernel> git checkout main
Switched to branch 'main'
Your branch is up to date with 'origin/main'.
PS D:\FreeRTOS-Kernel> git branch -D dev/my_branch
Deleted branch dev/my_branch (was 81c623212).
PS D:\FreeRTOS-Kernel> git branch
* main
  smp
PS D:\FreeRTOS-Kernel>

3.4 add

git add [--verbose | -v] [--dry-run | -n] [--force | -f] [--interactive | -i] [--patch | -p]
	  [--edit | -e] [--[no-]all | -A | --[no-]ignore-removal | [--update | -u]] [--sparse]
	  [--intent-to-add | -N] [--refresh] [--ignore-errors] [--ignore-missing] [--renormalize]
	  [--chmod=(+|-)x] [--pathspec-from-file=<file> [--pathspec-file-nul]]
	  [--] [<pathspec>…​]

官网原文:

This command updates the index using the current content found in the working tree, to prepare the content staged for the next commit. It typically adds the current content of existing paths as a whole, but with some options it can also be used to add content with only part of the changes made to the working tree files applied, or remove paths that do not exist in the working tree anymore.

The "index" holds a snapshot of the content of the working tree, and it is this snapshot that is taken as the contents of the next commit. Thus after making any changes to the working tree, and before running the commit command, you must use the add command to add any new or modified files to the index.

This command can be performed multiple times before a commit. It only adds the content of the specified file(s) at the time the add command is run; if you want subsequent changes included in the next commit, then you must run git add again to add the new content to the index.

The git status command can be used to obtain a summary of which files have changes that are staged for the next commit.

The git add command will not add ignored files by default. If any ignored files were explicitly specified on the command line, git add will fail with a list of ignored files. Ignored files reached by directory recursion or filename globbing performed by Git (quote your globs before the shell) will be silently ignored. The git add command can be used to add ignored files with the -f (force) option.

中文翻译:

该命令使用工作树中当前的内容更新索引,以准备将内容暂存至下一次提交。通常,它会将现有路径的当前内容作为整体添加到索引中,但使用某些选项时,也可以仅将部分工作树文件的更改应用于添加的内容,或者移除工作树中不再存在的路径。

"索引"保存着工作树内容的快照,而正是这个快照被视为下一次提交的内容。因此,在对工作树进行任何更改之后,在运行提交命令之前,必须使用add命令将任何新的或修改过的文件添加到索引中。 在提交之前,可以多次执行此命令。它仅在运行add命令时添加指定文件的内容;如果希望将后续更改包含在下一次提交中,则必须再次运行git add命令,将新的内容添加到索引中。

可以使用git status命令获取一个概要,其中列出了哪些文件具有已暂存的更改,准备提交至下一次提交。 默认情况下,git add命令不会添加被忽略的文件。如果在命令行上明确指定了任何被忽略的文件,git add将失败,并显示被忽略的文件列表。Git通过目录递归或文件名通配符(在Shell之前引用通配符)进行的递归会自动忽略被忽略的文件。可以使用-f(force)选项强制git add命令添加被忽略的文件。

例程说明:将文件内容添加到索引中,当本地的文件有改动时,需要把最新的文件内存暂存到下一次提交中。比如文件夹里面多出了一个test.md文件时,我们就可以用add命令来增加。

 在powershell中输入如下指令

touch test.md
git status
git add .
git status

运行结果

PS D:\FreeRTOS-Kernel> touch test.md
PS D:\FreeRTOS-Kernel> git status
On branch main
Your branch is up to date with 'origin/main'.

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        test.md

nothing added to commit but untracked files present (use "git add" to track)
PS D:\FreeRTOS-Kernel> git add .
PS D:\FreeRTOS-Kernel> git status
On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   test.md

PS D:\FreeRTOS-Kernel>

3.5 commit

git commit [-a | --interactive | --patch] [-s] [-v] [-u<mode>] [--amend]
	   [--dry-run] [(-c | -C | --squash) <commit> | --fixup [(amend|reword):]<commit>)]
	   [-F <file> | -m <msg>] [--reset-author] [--allow-empty]
	   [--allow-empty-message] [--no-verify] [-e] [--author=<author>]
	   [--date=<date>] [--cleanup=<mode>] [--[no-]status]
	   [-i | -o] [--pathspec-from-file=<file> [--pathspec-file-nul]]
	   [(--trailer <token>[(=|:)<value>])…​] [-S[<keyid>]]
	   [--] [<pathspec>…​]

官网原文:

Create a new commit containing the current contents of the index and the given log message describing the changes. The new commit is a direct child of HEAD, usually the tip of the current branch, and the branch is updated to point to it (unless no branch is associated with the working tree, in which case HEAD is "detached" as described in git checkout

中文翻译:

创建一个新的提交,其中包含索引的当前内容和给定的日志消息,用于描述更改。新的提交是HEAD的直接子节点,通常是当前分支的尖端,并且分支会更新为指向它(除非工作树没有关联的分支,此时HEAD会像git-checkout[1]中描述的那样“分离”)。

例程说明:将更改记录到本地仓库中,最常使用的就是 git commit -m “commit Message(自定义)”


 在powershell中输入如下指令

git status
git commit -m "Add Test Commit message"
git log

运行结果如下

PS D:\FreeRTOS-Kernel> git status
On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   test.md

PS D:\FreeRTOS-Kernel> git commit -m "Add Test Commit message"
[main 71e4ccb03] Add Test Commit message
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 test.md
PS D:\FreeRTOS-Kernel> git log
commit 71e4ccb03366316ba3a497f9d27c687f922c7934 (HEAD -> main)
Author: boxiong <zhaoboxiong@xyl.cn>
Date:   Tue Apr 2 16:05:43 2024 +0800

    Add Test Commit message

commit 52ee9faa72f2f67f04752c9d89b7b48c804bfa66 (origin/main, origin/HEAD)
Author: Soren Ptak <ptaksoren@gmail.com>
Date:   Thu Mar 28 22:37:38 2024 -0700

3.6 push

git push [--all | --branches | --mirror | --tags] [--follow-tags] [--atomic] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
	   [--repo=<repository>] [-f | --force] [-d | --delete] [--prune] [-q | --quiet] [-v | --verbose]
	   [-u | --set-upstream] [-o <string> | --push-option=<string>]
	   [--[no-]signed|--signed=(true|false|if-asked)]
	   [--force-with-lease[=<refname>[:<expect>]] [--force-if-includes]]
	   [--no-verify] [<repository> [<refspec>…​]]

官网原文:

Updates remote refs using local refs, while sending objects necessary to complete the given refs.

When the command line does not specify where to push with the <repository> argument, branch.*.remote configuration for the current branch is consulted to determine where to push. If the configuration is missing, it defaults to origin.

When neither the command-line nor the configuration specifies what to push, the default behavior is used, which corresponds to the simple value for push.default: the current branch is pushed to the corresponding upstream branch, but as a safety measure, the push is aborted if the upstream branch does not have the same name as the local one.

中文翻译:

使用本地引用更新远程引用,同时发送完成给定引用所需的对象。 

当命令行中的<repository>参数没有指定推送的位置时,会查询当前分支的branch.*.remote配置来确定推送的位置。如果配置缺失,则默认为origin。当命令行和配置都没有指定要推送的内容时,将使用默认行为,即对应于push.default的简单值:将当前分支推送到相应的上游分支,但为了安全起见,如果上游分支的名称与本地分支不同,推送将被中止。

 例程说明:将内容同步到远程仓库中,最常用的就是git push origin HEAD

 在powershell中输入如下指令

git push origin HEAD

由于我们没有目标仓库的push权限,push命令将被拒绝,关于ssh访问权限的获取我们将在下一篇文章中进行详细讲解。

PS D:\FreeRTOS-Kernel> git push origin HEAD
ERROR: Permission to FreeRTOS/FreeRTOS-Kernel.git denied to xxx.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
PS D:\FreeRTOS-Kernel>

那么关于push命令的举例,我们会利用作者的私人仓库中进行说明, 在powershell中输入

git status
git add .
git commit -m "自己想要输入的信息"
git push origin HEAD

运行结果如

PS D:\mqtt\python_mqtt> git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   mqtt_device_ec800_usb.xml

no changes added to commit (use "git add" and/or "git commit -a")
PS D:\mqtt\python_mqtt> git add .
PS D:\mqtt\python_mqtt> git commit -m "fix config of device ec800"
[master bd75bba] fix config of device ec800
 1 file changed, 1 insertion(+), 1 deletion(-)
PS D:\mqtt\python_mqtt> git push origin HEAD
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 12 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 299 bytes | 299.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
To github.com:xxx/mqtt_uart.git
   3784172..bd75bba  HEAD -> master
PS D:\mqtt\python_mqtt>

3.7 pull

git pull [<options>] [<repository> [<refspec>…​]]

官网原文:

Incorporates changes from a remote repository into the current branch. If the current branch is behind the remote, then by default it will fast-forward the current branch to match the remote. If the current branch and the remote have diverged, the user needs to specify how to reconcile the divergent branches with --rebase or --no-rebase (or the corresponding configuration option in pull.rebase).

中文翻译:

将远程仓库的更改合并到当前分支。如果当前分支落后于远程分支,则默认情况下会快进当前分支以与远程分支匹配。如果当前分支和远程分支发生了分歧,用户需要使用--rebase或--no-rebase(或相应的配置选项pull.rebase)来指定如何协调这些分歧的分支。

例程说明:pull的用途其实就是把远程仓库端的代码同步到本地。

 

在powershell中输入如下指令

git branch | grep develop
git pull
git log

运行结果

PS D:\jenkins_build\rh850> git branch | grep develop
* develop/mcu1.00_dev
PS D:\jenkins_build\rh850> git pull
remote: Counting objects: 607, done
remote: Finding sources: 100% (17/17)
remote: Total 17 (delta 12), reused 17 (delta 12)
Unpacking objects: 100% (17/17), 2.23 KiB | 14.00 KiB/s, done.
From ssh://172.30.10.205:29418/rh850
   67b6cee..08d5c1b  mcu_main_branch_xxx  -> origin/mcu_main_branch_xxx
 * [new branch]      xxx/mcu1.00_dev1 -> origin/xxx/mcu1.00_dev1
Already up to date.
PS D:\jenkins_build\rh850> git log
commit eab1795ca7a68c051a42c1fdd70555b373469df2 (HEAD -> develop/mcu1.00_dev, origin/xxx/mcu1.00_dev1, origin/develop/mcu1.00_dev)
Author: xxx <xxx@xxx.cn>
Date:   Sat Mar 30 17:22:59 2024 +0800

    add com timeout cfg

commit 1a3d1536c83a908e2b7ed29a520a6da2cb522f0a
Author: xxx <xxx@xxx.cn>
Date:   Sat Mar 30 16:56:38 2024 +0800

    Squashed commit of the following:

    commit 715dd547850f45de50860b7317e92f8aa4596e97
    Author: xxx <xxx@xxx.cn>
    Date:   Tue Mar 19 20:32:16 2024 +0800

        add can timeout diag

commit 3ea9f451300ae09555672654fdda140ce980229d
Author: xxx <xxx@xxx.cn>
Date:   Sat Mar 30 16:42:48 2024 +0800

    Squashed commit of the following:

    commit b057bfc2bc31910a940a3b14020c3fde431d28bf
    Author: xxx <xxx@xxx.cn>
    Date:   Fri Mar 29 20:15:24 2024 +0800

        update spi Tx Transmit

4. 结语

本文旨在介绍git使用中的最基本的命令,辅以作者自己的操作例程,希望能对大家学习git有所帮助,后面作者将会继续更新git的各种高级用法,敬请期待。

  • 28
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

废柴程序员-熊熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值