Git学习笔记(一):基础与应用

简介: 本文档详细介绍了如何将本地项目关联到Gitee上的空仓库并上传代码,以及如何验证本机与Git服务器的SSH连接。同时,还概述了Git的基本概念、安装步骤、初始配置、常见命令及如何配置多个SSH-Key,适用于初学者快速上手Git操作。

FAQ

1、怎么将一个本地项目,关联到一个空的gitee仓库,并将代码上传?

  1. 首先,在gitee创建一个空仓库,如springexecute
  2. 其次,在本地工程根目录初始化git工程,git init
  3. 然后,将一个远程仓库添加到本地仓库中,git remote add origin [url]
  4. 接着,拉取远程仓库到本地,在将本地仓库文件纳入版本控制,并提交推送git pull /git push
  5. 按照第4步直接拉推会提示你关联本地与远程分支,故执行git branch --set-upstream-to=origin/master master,将本地仓库与远程仓库分支关联
  6. 分支关联后,git pull  出现 fatal: refusing to merge unrelated histories,使用参数--allow-unrelated-histories强行合并两个分支 git pull origin master  --allow-unrelated-histories,如果存在冲突,需要处理。
  7. 最终就完成了本地仓库与远程仓库的关联,可以正常推拉代码。

在Gitee创建一个空仓库时,会给出提示,但是我一开始创建了模版,所以没有快速设置。

2、如何验证本机与Git服务器是否已建立ssh连接?

$ ssh -T git@gitee.com
Hi SheeperZhang(@sheeperzhang)! You've successfully authenticated, but GITEE.COM does not provide shell access.

一、Git简述

Git是linus Torvalds为帮助管理Linux内核开发而开发的一个开放源码的分布式版本控制系统。(这段故事堪称软件史上最伟大的个人英雄主义之一)

与过去常见的CVS、SVN(Subversion)等版本控制系统采用的集中式管理不同,Git采用了分布式版本库的方式。

Git从诞生的那一刻,其血脉中就有开源社区的血液在流动。随后,在开源社区和广大开发者的努力下,它日臻完善。

特点:

  1. 简单易用
  2. 速度快
  3. 非线性分支管理
  4. 完全分布式
  5. 能够满足各种复杂项目的要求

二、Git安装

Windows下

http://git-scm.com/download 上下载window版的客户端,以管理员身份运行后,一直选择下一步安装即可,请注意,如果你不熟悉每个选项的意思,请保持默认的选项

CentOS/RedHat下

在终端下执行 yum install git

代码编译安装

https://github.com/git/git/releases 上选取一个版本下载,解压缩后进入到 Git 的目录然后依次执行以下代码:

make configure
./configure
make all
sudo make install

注意:如果遇上无法编译的问题,请自行通过搜索引擎来查找 Git 所需的依赖

验证

$ git --version
git version 2.36.1.windows.1

三、Git初始配置

在新环境首次使用Git时,需要先配置Git工作环境,仅需配置一次,相同命令随时修改。

Git提供了git config(实际是git-config命令)工具用于配置或读取相应的工作环境变量。而这些环境变量也决定了Git的具体工作方式和行为。

git config

(1)配置存放位置:

  1. /etc/gitconfig文件(win:本机D:\SheepRunner\Developer\Git\etc\gitconfig):存放所有用户普遍适用的配置。git config --system读写这个文件。
  2. ~/.gitconfig文件(win:本机C:\Users\84204\.gitconfig):存放在用户目录下,仅适用于该用户。 git config --global读写这个文件。
  3. 当前项目仓库下的.git/config文件(win:本机D:\SheepRunner\GitProjects\springexecute\.git\config):进存放当前仓库的配置。git config不加参数时读写该文件。

每一个级别的配置都会自动覆盖上一级的配置。全局system<用户global<仓库default。

(2)用户信息配置

设置用户名:git config --global user.name "SheepRunner"

设置邮箱:git config --global user.email "842049421@qq.com"

上面的参数--global 表示对当前用户生效,配置到了用户目录下的.gitconfig文件中,如果想要针对仓库配置,可以去除参数,配置就会到仓库下的.git/config文件。

如果使用https进行仓库的推拉,可能希望客户端记住密码,避免每次输入:

git config --global credential.helper store

(3)文本编辑器配置

默认文本编辑器。Git输入额外消息时,自动调用一个外部的文本编辑器,默认一般时vi或vim,也可以根据喜好配置其他,如emacs:

git config --global core.editor emacs

默认差异分析工具。在解决合并冲突时使用那种差异分析工具,Git可以理解kdiff3、tkdiff、meld、xxdiff、emerge、vimdiff、gvimdiff、ecmerge、opendiff等,也可以自行指定开发的工具,如vimdiff:

git config --global merge.tool vimdiff

文本编辑器和差异分析工具在现今的实际使用中并不常修改,现在很多集成开发工具都配备更加人性化的图形用户界面等。

(4)查看配置信息

检查所有的配置信息,包括全局、用户和仓库的。因此会存在同名的变量,而在当前仓库下,生效的事最后一个。如果只要查询全局或用户的,可以带上参数--global

$ git config --list
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
http.sslbackend=openssl
http.sslcainfo=D:/SheepRunner/Developer/Git/mingw64/ssl/certs/ca-bundle.crt
core.autocrlf=true
core.fscache=true
core.symlinks=false
core.longpaths=true
pull.rebase=false
credential.helper=manager-core
credential.https://dev.azure.com.usehttppath=true
init.defaultbranch=master
user.name=zhangyang
user.email=zhangyang@epoint.com.cn
filesystem.Oracle Corporation|1.8.0_201|412211110.timestampresolution=16001 microseconds
filesystem.Oracle Corporation|1.8.0_201|412211110.minracythreshold=0 nanoseconds
credential.https://gitee.com.provider=generic
difftool.sourcetree.cmd='' "$LOCAL" "$REMOTE"
mergetool.sourcetree.cmd=''
mergetool.sourcetree.trustexitcode=true
credential.helper=manager-core
credential.http://192.168.0.200.provider=generic
filesystem.Temurin|1.8.0_312|412211110.timestampresolution=2001 microseconds
filesystem.Temurin|1.8.0_312|412211110.minracythreshold=0 nanoseconds
safe.directory=*
filesystem.Oracle Corporation|17.0.7|412211110.timestampresolution=1176 microseconds
filesystem.Oracle Corporation|17.0.7|412211110.minracythreshold=0 nanoseconds
credential.https://codeup.aliyun.com.provider=generic
alias.last=log -1 HEAD
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true

也可以单独查询某个变量,直接将变量名跟在后面即可

$ git config user.name
zhangyang

四、Git帮助

可以通过在命令行中调用帮助命令来了解各种工具的具体用法,方法有三:

  1. git help [命令名]
  2. git [命令名] --help
  3. man git-[命令名]

比如,想要学习config命令怎么使用,可以运行

  1. $ git help config:打开本地的帮助文档

  1. $ git config --help:同上
  2. man在Windows系统不支持
  3. git config -h:另一种查看帮助的方式,在命令行中显示
$ git config -h
usage: git config [<options>]
Config file location
    --global              use global config file
    --system              use system config file
    --local               use repository config file
    --worktree            use per-worktree config file
    -f, --file <file>     use given config file
    --blob <blob-id>      read config from given blob object
Action
    --get                 get value: name [value-pattern]
    --get-all             get all values: key [value-pattern]
    --get-regexp          get values for regexp: name-regex [value-pattern]
    --get-urlmatch        get value specific for the URL: section[.var] URL
    --replace-all         replace all matching variables: name value [value-pattern]
    --add                 add a new variable: name value
    --unset               remove a variable: name [value-pattern]
    --unset-all           remove all matches: name [value-pattern]
    --rename-section      rename section: old-name new-name
    --remove-section      remove a section: name
    -l, --list            list all
    --fixed-value         use string equality when comparing values to 'value-pattern'
    -e, --edit            open an editor
    --get-color           find the color configured: slot [default]
    --get-colorbool       find the color setting: slot [stdout-is-tty]
Type
    -t, --type <type>     value is given this type
    --bool                value is "true" or "false"
    --int                 value is decimal number
    --bool-or-int         value is --bool or --int
    --bool-or-str         value is --bool or string
    --path                value is a path (file or directory name)
    --expiry-date         value is an expiry date
Other
    -z, --null            terminate values with NUL byte
    --name-only           show variable names only
    --includes            respect include directives on lookup
    --show-origin         show origin of config (file, standard input, blob, command line)
    --show-scope          show scope of config (worktree, local, global, system, command)
    --default <value>     with --get, use default value when missing entry

五、Git仓库创建

(1)在本地工作目录中初始化仓库

进入项目所在根目录,执行git init将初始化为Git仓库。在当前目录下出现一个.git目录,所有Git所需的数据和资源都在这个目录中。

$ git init
Reinitialized existing Git repository in D:/SheepRunner/GitProjects/springexecute/.git/

在本地仓库中,使用如下命令将文件纳入版本控制;

git add [filename or regular]:将本地文件纳入Git版本控制,可以文件全名或者正则表达式,所有文件用*表示

git commit -m '[message]':提交所有纳入版本控制的文件

git status:查看当前仓库的文件状态

(2)从现有仓库克隆

从已有的Git仓库中复制一份到本地,执行git clone [url]

git clone [url] [alias]

$ git clone git@gitee.com:sheeperzhang/springexecute.git
Cloning into 'springexecute'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (4/4), 4.91 KiB | 628.00 KiB/s, done.
84204@SheepRunner MINGW64 /f/tempdocs/codes
$ cd springexecute/
84204@SheepRunner MINGW64 /f/tempdocs/codes/springexecute (master)
$ ls -al
total 21
drwxr-xr-x 1 84204 197609     0 Nov 10 21:52 ./
drwxr-xr-x 1 84204 197609     0 Nov 10 21:52 ../
drwxr-xr-x 1 84204 197609     0 Nov 10 21:52 .git/
-rw-r--r-- 1 84204 197609   279 Nov 10 21:52 .gitignore
-rw-r--r-- 1 84204 197609 11558 Nov 10 21:52 LICENSE
84204@SheepRunner MINGW64 /f/tempdocs/codes/springexecute (master)
$ git status
On branch master

常用的克隆仓库协议为HTTPS和SSH。

需要注意的是,SSH协议方式需要先配置好ssh公钥,如果没有配置需要使用https协议地址,所幸现在的公共仓库都提供了两种地址。

六、Git基础命令

(1)git init

初始化一个本地Git仓库

(2)git add

将文件添加到Git暂存区

参数-A即--all, add changes from all tracked and untracked files,提交所有改动

(3)git status

查看仓库当前文件提交状态

参数-s即short,show status concisely,简洁展示状态(M修改,A提交成功,AM提交后又进行修改)

$ 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:   README.md
no changes added to commit (use "git add" and/or "git commit -a")
$ git status -s
 M README.md

(4)git commit

从Git暂存区提交版本到仓库

参数-m后为本次提交的备注信息

(5)git push/pull

将本地Git仓库信息推送上传服务器

相对应的,git pull表示从远程仓库拉取到本地

拉取时强行合并本地和远程分支,生成一个新的提交记录: git pull origin master  --allow-unrelated-histories

git pull还是git pull origin master

git pull拉取远程最新的内容,并合并到本地(git fetch,git merge),而git pull origin master只拉取选定的分支;前者还会自动处理冲突,而后者需要手动处理冲突。

(6)git log

查看git提交日志

git log -5  显示最近5条日志

(7)git remote

远程仓库管理

  1. 修改远程仓库名:git remote rename origin sheeprunner

默认远程仓库名都是origin,默认推拉时可以省略

  1. 添加一个远程仓库:git remote add origin [url]
  2. 查看当前仓库对应的远程仓库地址:git remote -v
$ git remote -v
origin  git@gitee.com:sheeperzhang/springexecute.git (fetch)
origin  git@gitee.com:sheeperzhang/springexecute.git (push)
  1. 修改远程仓库地址:git remote set-url origin [newurl]

(8)git branch

设置远程仓库与本地仓库分支关联:git branch --set-upstream-to=origin/master master

(9)git tag

打标签,一般用于稳定版本存档或发布

(10)git merge

合并分之间的代码

(11)git reset

撤销操作

git reset --hard 不可撤销,请谨慎操作,建议找到版本执行git reset vercode

(12)git stash

暂存,去开发别的代码,等到开发完成,使用git stash pop;查看暂存数git stash list

七、Git配置多SSH-Key

背景

在日常学习工作中,经常有需要对接多个远程仓库,比如:

  1. Gitee,用于公司内部工作开发
  2. GitHub,用户个人开发活动

生成公钥使用命令:ssh-keygen

ssh-keygen -t rsa -C [comment] -f [output_keyfile]

$ ssh-keygen --help
ssh-keygen: unknown option -- -
usage: ssh-keygen [-q] [-a rounds] [-b bits] [-C comment] [-f output_keyfile]
                  [-m format] [-N new_passphrase] [-O option]
                  [-t dsa | ecdsa | ecdsa-sk | ed25519 | ed25519-sk | rsa]
                  [-w provider] [-Z cipher]

解决方法

  1. 生成一个Gitee的SSH-Key

ssh-keygen -t rsa -C [comment] -f [output_keyfile]:ssh-keygen -t rsa -C 'xxx' -f ~/.ssh/gitee_id_rsa

  1. 生成一个GitHub的SSH-Key

ssh-keygen -t rsa -C [comment] -f [output_keyfile]:ssh-keygen -t rsa -C 'xxx' -f ~/.ssh/github_id_rsa

  1. 在~/.ssh目录下新建一个config文件,添加如下内容(其中Host和HostName填写git服务器的域名,IdentityFile指定私钥的路径)
# gitee
Host gitee.com
HostName gitee.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/gitee_id_rsa
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id_rsa
  1. 用ssh命令分别测试
ssh -T git@gitee.com
ssh -T git@github.com
$ ssh -T git@gitee.com
Hi SheeperZhang(@sheeperzhang)! You've successfully authenticated, but GITEE.COM does not provide shell access.
目录
相关文章
|
9月前
|
API 开发工具 git
git常用的API以及每个的应用场景
【4月更文挑战第5天】Git是流行的分布式版本控制系统,用于代码管理,提供丰富的API。本文概述了Git常用API,如`git init`(初始化仓库)、`git add`(添加到暂存区)、`git commit`(提交)、`git remote add origin`(添加远程仓库)、`git pull`和`push`(同步远程仓库)、`git branch`(分支管理)以及`git checkout`(切换分支或恢复文件)。了解和熟练使用这些API能提升开发效率和代码质量,更多Git功能可参考官方文档。
449 0
|
9月前
|
测试技术 持续交付 开发工具
《Git 简易速速上手小册》第6章:Git 在持续集成/持续部署(CI/CD)中的应用(2024 最新版)
《Git 简易速速上手小册》第6章:Git 在持续集成/持续部署(CI/CD)中的应用(2024 最新版)
142 2
|
测试技术 Linux 开发工具
Git之分支与版本->课程目标及知识点的应用场景,分支的场景应用,标签的场景应用
Git之分支与版本->课程目标及知识点的应用场景,分支的场景应用,标签的场景应用
85 0
|
6月前
|
安全 Linux 开发工具
Git学习笔记
这篇文章是一份Git学习笔记,涵盖了Git的基本命令、工作流程、项目搭建、文件状态管理,以及如何使用码云和IDEA进行版本控制操作。
Git学习笔记
|
9月前
|
Shell 网络安全 开发工具
Git学习笔记
Git学习笔记
146 1
Git学习笔记
|
6月前
|
存储 Linux 开发工具
【Azure App Service】本地Git部署Python Flask应用上云(Azure App Service For Linux)关键错误
【Azure App Service】本地Git部署Python Flask应用上云(Azure App Service For Linux)关键错误
|
6月前
|
jenkins 测试技术 开发工具
协同开发的艺术:Git 在团队项目中的高效应用
【8月更文第16天】在现代软件开发中,团队成员之间的高效协作是至关重要的。Git 作为一种分布式版本控制系统,为开发者提供了强大的工具来管理代码的变化和协作。本文将介绍如何利用 Git 来优化团队的工作流程,并提供实际操作的代码示例。
200 1
|
7月前
|
存储 安全 开发工具
Git学习笔记 三个区域、文件状态、分支、常用命令
理解并掌握这些概念和命令,对于有效地使用Git来管理项目源代码是至关重要的。Git的强大功能支持了复杂的开发工作流程,而良好的Git实践能够极大地提高团队的协作效率。随着实践的增多,对于Git更深层次的功能和最佳实践的理解也会随之增长,进一步加强你作为一个软件开发者的能力。
88 0
|
8月前
|
前端开发 持续交付 开发工具
详细介绍Git的基本原理、在前端开发中的应用以及如何使用Git来优化团队协作
【6月更文挑战第14天】Git是前端开发中的必备工具,它通过分布式版本控制管理代码历史,支持分支、合并和冲突解决,促进团队协作。在前端开发中,Git用于代码追踪、版本控制、代码审查和持续集成部署,优化团队协作。制定分支策略、编写清晰提交信息、定期合并清理分支以及使用Git钩子和自动化工具能进一步提升效率。理解并善用Git,能有效提升前端项目的质量和开发效率。
96 3
|
8月前
|
中间件 Java 生物认证
Web应用&源码泄漏&开源闭源&指纹识别&GIT&SVN&DS&备份
Web应用&源码泄漏&开源闭源&指纹识别&GIT&SVN&DS&备份