本文记录Git常用命令。

1 Git常用命令

1.1 查询命令

1
2
3
4
5
git status # 查看当前git状态
git log    # 查询修改记录
git tag -l # 查询tag
# git log精简模式显示指定信息
git log --pretty=format:"%h,%an,%aI,%s" | head

1.2 代码下载上传

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# down load source code
git clone -b main git@github.com:alvincat/MyGithubWebsite.git MyWebsite

# recurse update submodule
git submodule update --init --recursive
git push 

# pull = fetch + merge
# pull --rebase = fetch + rebase
# so recommand use: git pull --rebase
git pull --rebase

git push --set-upstream origin gh_pages # upload new branch
# or 
git push -u origin <your_branch_name>

1.3 分支相关操作

1
2
3
4
5
6
git branch # 查看本地所有分支
git branch | grep "*"  #查看当前分支
git checkout branch_name # 切换分支
git checkout -b gh_pages # create branch
git branch -D gh_pages   # 删除本地分支
git push origin --delete main  # 删除远端分支

1.4 修改相关操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
git commit -m ""     # add commit
git add file1 file2  # add to local cache

git stash     # 暂存当前修改
git stash pop # 恢复暂存内容

git reset --hard origin/master # 强制更新当前分支代码为master分支
git reset --mixed commit_id    # 将制定commit_id以后的提交回退至未提交
git rebase -i head~2

git cherry-pick commit_id

1.5 远程仓库操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 查询本地关联的代码仓
git remote -v

# 修改代码仓地址
git remote add origin url xxx

# 添加远程分支, 其中origin为远程代码仓在本地的name, 本地代码可以关联多个远程代码仓
git remote origin  https://github.com/olOwOlo/hugo-theme-even
git remote add myEvenBackup git@github.com:alvincat/HugoThemeEven.git

# 提交代码时可以指定代码仓进行
# 提交代码至https://github.com/olOwOlo/hugo-theme-even的master分支
git push -u origin master
# 提交代码至git@github.com:alvincat/HugoThemeEven.git的master分支
git push -u myEvenBackup master

2 Git相关配置

2.1 Git添加ssh公钥

  1. 设置用户名和邮箱

    1
    2
    
    # 设置用户名
    git config --global user.name "username"
    

设置邮箱

git config –global user.email your_email@example.com

查看用户名和密码

git config user.name git config user.email

查看其他配置信息(git设置列表)

git config –list

1
2
3
4
5
2. 执行命令生成ssh公钥和私钥
+ windows环境
```shell
# 使用Ed25519加密算法生成公钥和私钥
ssh-keygen -t ed25519 -C "your_email@example.com"
  • Linux或者MacOS环境

    1
    2
    
    # 使用Ed25519加密算法生成公钥和私钥
    ssh-keygen -t ed25519-sk -C "your_email@example.com"
    
  1. 将生成的公钥文件id_ed25519.pub中的内容添加至github即可使用ssh上传下载代码。

温馨提示:
若添加公钥后,提交代码提示错误:push declined due to email privacy restrictions
原因:将github关联的email设置为私密,对外不可见。
解决方法:

  1. 方法1:进入https://github.com/settings/emails页面,将【Block command line pushes that expose my email】勾选去掉。
  2. 方法2:使用github提供的转换邮件地址。(在标签【Keep my email addresses private】的内容中提供,形如:12345678+username@users.noreply.github.com)。使用这个邮件地址更新密钥即可。

2.2 gitignore的用法

git在提交代码时,存在部分本地生成的和代码无关的文件,不需要提交。这种文件或者目录就需要使用gitignore的机制进行过滤。使用方法如下:

  1. 在代码根目录创建文件.gitignore
  2. 在文件中添加需要过滤的文件和目录,注意若要过滤整个目录,需要在目录后跟/

常见情况解决方法:

  1. 添加到.gitignore文件中的目录,再次提交后并未生效。解决方法,执行代码:git rm -r --cached <folder>