Skip to content

Git

Git常用命令

  • 取消git pull/push时频繁输入账号密码

    Bash
    git config --global credential.helper store
    
  • git出现^M符号

    Bash
    1
    2
    3
    # 这是因为windows是CRLF回车换行,mac/linux是LF
    # 使用下方命令解决
    git config --global core.autocrlf input
    
  • git error: object file xxx is empty

    Bash
    1
    2
    3
    4
    5
    6
    # 删除空的object文件
    find .git/objects/ -type f -empty | xargs rm
    # 重新 fetch 远端的分支,并 prune 修剪掉远端已经无效的分支
    git fetch -p
    # file system check,进行仓库的一致性检查
    git fsck --full
    
  • git 重命名分支

    Bash
    1
    2
    3
    4
    # 重命名当前分支
    git branch -m new_name
    # 重命名其他分支
    git branch -m old_name new_name
    
  • git commit后撤销commit:

    Bash
    1
    2
    3
    4
    git reset --soft HEAD^
    # HEAD^表示上一个版本,同HEAD~1
    # --soft 不删除工作空间的改动代码,撤销commit,不撤销git add file
    # --hard 删除工作空间的改动代码,撤销commit并撤销add
    
  • git 取消add操作:

    Bash
    # 整体回到上一次操作,后跟文件名是针对文件进行回滚
    git reset HEAED
    
  • git reset --hard丢失改动信息,可在30天内通过git reflog查看改动与恢复

  • git stash 保存备注信息

    Bash
    git stash save "msg"
    
  • git stash 部分文件

    借用git add实现

    Bash
    1
    2
    3
    git add file1 file 2 # 保留更改文件到工作区
    git stash save -k # 暂存未add的更改文件
    git reset #回复工作区文件
    
  • git 保存patch

    Bash
    1
    2
    3
    4
    5
    # 将最新提交保存为patch
    git format-patch HEAD^
    git diff > changes.patch
    # stash 导出为patch
    git stash show "stash@{0}" -p > changes.patch
    
  • git 应用patch

    Bash
    1
    2
    3
    4
    git apply xxx.patch
    # --3way  合并如果失败,采用3way算法进行合并
    # --reject 采用上述方法失败后,可自行解决.rej的文件冲突
    # --whitespace=fix 忽略空格
    
  • git 取消应用patch

    Bash
    git apply -R changes.patch
    
  • git fork分支后与原仓库保持同步

    参考链接

    Bash
    # 克隆新仓库
    git clone xxx/newhub.git
    # 在新仓库添加原仓库的远程链接
    git remote add oldhub xxx/oldhub.git
    # git remote -v 可以看到新仓库origin和旧仓库oldhub的仓库信息
    # 获取远程仓库内容
    git fetch oldhub
    # git branch -r 可以看到两个仓库的所有分支信息
    # 使用merge同步分支,在newhub/master下
    git merge oldhub/master --allow-unrelated-histories # merge出错使用
    
  • git合并一个分支的指定commit到另一个分支

    Bash
    git cherry-pick [commit-id]
    
  • git 分支绑定

    Bash
    git branch --set-upstream-to=origin/develop develop
    

Repo命令

  1. 同步:repo sync -c -> repo forall -c 'git lfs pull'
  2. 删除本地修改并同步:repo sync -d
  3. repo 重新init前需要reset所有分支,去除所有改动

    Bash
    1
    2
    3
    # 全部重置方法
    # 其中 clean -f 表示删除当前目录下没有track过的文件,-d表示包括文件夹
    repo forall -c 'git reset --hard && git clean -fd'
    
  4. repo 全仓库回退到某个时间提交之前

    Bash
    repo forall -c 'commitID=`git log --before "2023-04-28 00:00" -1 --pretty=format:"%H"`; git reset --hard $commitID'