git常用命令

141 阅读3分钟

clone(克隆代码)

// 克隆项目到本地
git clone 远程仓库克隆地址
// 克隆远程指定分支
git clone -b 远程分支名 远程仓库克隆地址

add(暂存代码)

// 将文件添加到暂存区
git add ./

commit(提交代码)

// 从暂存区提交到仓库区
git commit -m '描述信息'
// 添加到暂存区并提交到仓库区
git commit -am '描述信息'

pull(拉取最新代码)

// 拉取远程 origin 仓库的 master 分支的最新代码
git pull origin 远程分支

push(推送代码)

// 将本地的 master 分支推送到远程 origin 仓库的 master 分支
git push origin master(本地分支):master(远程分支)
// --force: 强制推送到远程
git push origin master --force

remote(关联远程仓库)

// 将远程 origin 仓库与本地进行关联
git remote add origin(名字随便取) 远程仓库克隆地址

branch(查看或创建分支)

// 列出所有分支
git branch
// 创建新分支
git branch 新分支名

checkout(切换分支)

// 切换分支
git checkout 分支名
// 创建并切换到该分支
git checkout -b 分支名

stash(暂时存储)

  • 单个stash
// 暂时存储起来(如遇到一个比较紧急的bug,可以先执行此命令暂存起来,不提交)
git stash
// 将暂存的代码释放出来,继续开发(stash列表记录删除)
// git stash pop
// 将暂存的代码释放出来,继续开发(stash列表记录保留)
git stash apply
  • 多个stash
// 暂存并添加描述信息
git stash save '描述信息'
// 查看所有暂存的stash
git stash list
// 将第二个暂存的代码释放出来
git stash apply stash@{1}

reflog(查看日志)

// 查看历史提交记录
git log
// 查看所有分支的所有操作记录(包括commit和reset操作),包括已经被删除的commit记录,git log 则不能察看已经删除了的commit记录
git reflog

reset(版本回退)

// 回退到上一个版本
git reset --hard HEAD^
// 先通过git reflog查看历史版本号,再通过版本号回退到指定版本
git reset --hard 版本号

合并多次提交

参考: 使用git rebase合并多次commit

  • 将本次提交合并到上一次提交
    1. git commit --amend
    2. 保存: wq 或 x
    3. 强制推送(注意: 本地分支可能会改变)
  • 合并多次提交
  /* 查看历史提交记录,找到要合并的始末提交记录
    startpoint: 较早的提交记录的前一个提交
    endpoint: 靠后的提交记录(可以不填,默认是最新的那次提交)
    [startpoint, endpoint]: 合并这个提交区间
  */
  git rebase -i startpoint endpoint
  /*
    pick 47971f6 fix: 第一次提交
    s d2cf1f9 fix: 第二次提交
    s wgacf1f fix: 第三次提交
  */
  除了第一次提交,其他提交前面的pick都改为s
  保存: wq 或 x
  删除其他提交信息: dd删除行
  保存: wq 或 x
  强制推送(注意: 本地分支可能会改变)

代码提交量统计

// 统计指定时间内个人的代码提交量
git log --since ==2020-06-1 --until=2020-06-6 --author="$(git config --get user.name)" --pretty=tformat: --numstat | awk '{ add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", add, subs, loc }'