Git 学习笔记
本文最后更新于 609 天前,其中的信息可能已经有所发展或是发生改变。

Git

准备工作

安装

官网下载

macOS

brew install git

Linux

sudo apt-get install git

查看版本信息/是否安装

git --version

生成SSH密钥

输入 ls -al ~/.ssh 查看是否存在SSH keys

ls -al ~/.ssh
# Lists the files in your .ssh directory, if they exist

查看是否生成过public SSH key。默认情况下GitHub支持的public keys文件名如下:

  • id_rsa.pub
  • id_ecdsa.pub
  • id_ed25519.pub

若已存在则跳过下面步骤。

Generating a new SSH key and adding it to the ssh-agent

使用 SSH 密钥密码

使用 SSH 密钥时,如果有人获得您计算机的访问权限,他们也可以使用该密钥访问每个系统。 要添加额外的安全层,可以向 SSH 密钥添加密码。 您可以使用 ssh-agent 安全地保存密码,从而不必重新输入。

Working with SSH key passphrases

添加SSH密钥

Adding a new SSH key to your GitHub account

cat ~/.ssh/id_ed25519.pub
  # Then select and copy the contents of the id_ed25519.pub file
  # displayed in the terminal to your clipboard

测试SSH连接

ssh -T git@github.com
# Attempts to ssh to GitHub

可能会看到类似如下的warning

> The authenticity of host 'github.com (IP ADDRESS)' can't be established.
> RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
> Are you sure you want to continue connecting (yes/no)?

公钥指纹可用于验证与远程服务器的连接。以下是 GitHub 的公钥指纹:

  • SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8 (RSA)
  • SHA256:p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM (ECDSA)
  • SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU (Ed25519)

验证无误后输入yes

> Hi USERNAME! You've successfully authenticated, but GitHub does not
> provide shell access.

初始化用户信息/更改配置

git config --global user.email you@example.com
git config --global user.name "Your Name"

更改配置

git config --global -e
# This is Git's per-user configuration file.
[https]
    proxy = socks5://127.0.0.1:7890
[http]
    proxy = socks5://127.0.0.1:7890
[user]
    name = Your Name
    email = you@example.com
[core]
    editor = vim
    excludesfile = /Users/xxxx/.gitignore_global
[init]
    defaultBranch = main
[color]
    ui = true

关于main/master分支

本地main/master分支

GitHub于2020年对默认分支名进行了更改(见Renaming the default branch from master),因此建议将Git默认分支从master修改为main

git config --global init.defaultBranch main

否则后面输入git push origin main可能出现下列问题,因为Git默认的分支为master,没有main分支

git push origin main
  error: src refspec main does not match any
  error: failed to push some refs to 'github.com:.../....git'

解决办法如下:

# 切换到main分支并进入
git checkout -b main
  Switched to a new branch 'main'

# 删除本地的master分支
git branch -D master

# 创建新仓库的时候可能带有README.md文件,而本地没有,所以需要先拉取下来
git pull origin main --allow-unrelated-histories # 老版本:git pull origin main

# 然后就可以push了
git push origin main

GitHub main/master分支

假设把默认master分支更名为 main分支,此时有个本地clone,可以通过下面的指令更新仓库。

git branch -m master main
git fetch origin
git branch -u origin/main main
git remote set-head origin -a
CleanShot 2022-11-30 at 22.10.45@2x

项目管理

使用Git初始化本地仓库

git init # 初始化本地仓库

GitHub设置仓库

需要关注以下几个点:

关于README.md

README通常是访客访问仓库第一个看见的文件,内容一般包括但不限于介绍[1]

  • 这个项目是做什么的?
  • 为什么这个项目有用?
  • 如何着手使用该项目?
  • 从该项目能获得什么帮助?
  • 项目维护和贡献者。

如何规范书写✍️README.md

关于.gitignore

.gitignore是一个文本文件,它告诉Git要忽略项目中的哪些文件或文件夹。详细查看 .gitignore章节。

创建全局.gitignore

创建全局.gitignore文件,以定义忽略本机上每个 Git 存储库中文件的规则列表。 例如,在 ~/.gitignore_global 中创建文件并在其中加入一些规则。

配置 Git 对所有 Git 存储库使用排除文件 ~/.gitignore_global

git config --global core.excludesfile ~/.gitignore_global

关于Liicense的选择

如何选择合适的License?

本地设置远程仓库

GitHub官方文档

Git Basic – Working with Remotes

首先确保已使用Git初始化本地仓库,然后添加远程仓库:

The command takes two arguments:

  • A remote name, for example, origin
  • A remote URL, for example,
git remote add origin https://github.com/

git remote add指令需要两个参数:

  • 远程仓库名,如origin
  • 远程仓库地址,如https://github.com/user/repo.git

通过以下指令查看远程仓库信息:

git remote -v
# Verify new remote
> origin  https://github.com/YourName/Your-Projects-Name.git (fetch)
> origin  https://github.com/YourName/Your-Projects-Name.git (push)

接着就是获取更新某个分支:

# 从远程仓库中获取某个分支的更新,再与本地指定的分支进行自动merge
git pull origin main

# 上述指令相当于执行了以下指令
git fetch origin main
git checkout main
git merge origin/main

# 或者合并
git pull --rebase origin main

查找仓库来源

有时候忘记自己是从哪个地方下载的仓库,这时候可以进入git clone的文件夹根目录,在该处打开终端并输入

git reflog --date=iso|grep clone
d94ea16 HEAD@{2022-08-15 11:54:24 +0800}: clone: from git://g.csail.mit.edu/6.824-golabs-2022

设置与查看配置

Git的设置文件为.gitconfig,它可以在用户主目录下(全局配置),也可以在项目目录下(项目配置)

# 显示当前的Git配置
git config --list
# 编辑Git配置文件
git config [--global] -e 
# 设置提交代码时的用户信息
git config [--global] user.name "[name]"
git config [--global] user.email "[email address]"

# 字体配置
# Display UTF-8 characters in filenames, if you're having problems seeing them
git config --global core.quotepath false

# 颜色设置
git config --global color.ui true                    # git status等命令自动着色
git config --global color.status auto
git config --global color.diff auto
git config --global color.branch auto
git config --global color.interactive auto
git config --global --unset http.proxy               # remove proxy configuration on git
git config --global core.editor "nvim"               # git使用系统默认编辑器,在这里我改成nvim
git config --global core.editor "code --wait"
# 使用vscode打开,并等待关闭

git config --global diff.tool vscode                 # difftool名设为vscode
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE" # 设置启动vscode ⚠️注意config是否正确写入!

查看配置

git config --system --list   # 查看系统配置
git config --global --list   # 查看当前用户(global)配置
git config --local --list    # 查看当前仓库配置信息

.gitignore

本地.gitignore文件通常被放置在项目的根目录中。 你还可以创建一个全局.gitignore文件,该文件中的所有条目都会在你所有的Git 仓库中被忽略。

设置全局配置

创建全局.gitignore文件

vim ~/.gitignore

添加规则,如mac用户可忽略macOS自动创建的.DS_Store等。(更多

# General
.DS_Store

# Compiled Python files
*.pyc

# Compiled C++ files
*.out

也可以通过curl使用GitHub的默认macOS配置规则。

curl https://raw.githubusercontent.com/github/gitignore/master/Global/macOS.gitignore -o ~/.gitignore

在项目文件夹下可自定义规则,常用规则如下:

# ignore all .a files
*.a

# but do track lib.a, even though you're ignoring .a files above
!lib.a

# only ignore the TODO file in the current directory, not subdir/TODO
/TODO

# ignore all files in any directory named build
build/

# ignore doc/notes.txt, but not doc/server/arch.txt
doc/*.txt

# ignore all .pdf files in the doc/ directory and any of its subdirectories
doc/**/*.pdf

使用

如何查询某一指令的帮助文档

git add -h  # 查看git add的帮助信息

文件管理

添加track

git add .                 # 添加所有文件
git add ../apps/webget.cc # 添加指定文件

显示有关索引和工作树中文件的信息

git ls-files

删除文件

git rm -h # 查看帮助信息
# -r allow recursive removal
git rm -r --cached <file>   # 不删除本地文件
git rm -r --f <file>        # 删除本地文件

恢复文件

git restore <file>          # 在工作空间但是不在暂存区的文件撤销更改
git restore --staged <file> # 将暂存区的文件从暂存区撤出,但不会更改文件
git restore --source=HEAD~1 <file>

清理文件

git clean -fd # 删除当前目录下没有被track过的文件和文件夹
              # 工作目录和缓存区将回到最近一次commit的状态

commit

git commit -m "commit content"
git commit # 调用文本编辑器输入(适合大量内容)

commit的一些 实用技巧 花里胡哨的东西

  • 通过emoji更直观地呈现

版本查看/对比

git difftool [--staged]
git diff origin/main # 查看本地版本库和远程版本库的区别
# 列出历史提交记录
git log [--oneline] [--reverse]
git show d601b90 # or d60
git show HEAD~2  # HEAD往前2个版本
git show 1dcc30
git show HEAD~1:bin/app.bin # 查看具体文件内容

分支管理

git checkout master  # 切换到master分支
git merge lab0-2     # 合并分支
# push到远程仓库(如GitHub)
git push origin main
# 删除远程分支
git push origin --delete [branch name]
# 查看本地分支
git branch
# 查看远程分支
git branch -r
# 删除本地分支
git branch -D [branch name] # ⚠️是否已合并

查看信息

查看项目的当前状态,其中-s表示 short-format

git status [-s]
X          Y     Meaning
-------------------------------------------------
         [ AMD]  not updated
M        [ MTD]  updated in index
T        [ MTD]  type changed in index
A        [ MTD]  added to index
D                deleted from index
R        [ MTD]  renamed in index
C        [ MTD]  copied in index
[ MTARC]         index and work tree matches
[ MTARC]    M    work tree changed since index
[ MTARC]    T    type changed in work tree since index
[ MTARC]    D    deleted in work tree
            R    renamed in work tree
            C    copied in work tree
-------------------------------------------------
D           D    unmerged, both deleted
A           U    unmerged, added by us
U           D    unmerged, deleted by them
U           A    unmerged, added by them
D           U    unmerged, deleted by us
A           A    unmerged, both added
U           U    unmerged, both modified
-------------------------------------------------
?           ?    untracked
!           !    ignored
-------------------------------------------------

版本回滚

# 回滚到具体版本
git reset --hard&nbsp;commit_id

# 回退上个版本
git reset --hard HEAD^ 

# 回退上上个版本
git reset --hard HEAD^^

Git 对象

  1. Commits
  2. Blobs (Files)
  3. Trees (Directories)
  4. Tags

Git Aliases

Add & Commit

AliasAdd & Commit
gaagit add –all
gcgit cimmit -v
AliasWork in Progress
gstgit status

其他资料

MIT Version Control (Git)
Git Book
Git docs
常用指令
Git Aliases
Git Tutorial for Beginners: Learn Git in 1 Hour

参考

  1. ^https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-readmes
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 协议 。转载请注明出处!
您可以通过 RSS 订阅本站文章更新。

评论

  1. EchoForger
    Macintosh Safari
    2 年前
    2022-8-30 9:57:54

    👍Good

    • 博主
      EchoForger
      Macintosh Chrome
      2 年前
      2022-8-30 20:49:34

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇