Git回退

作者: 程序员丶星霖 | 来源:发表于2018-10-22 21:24 被阅读0次

    一、checkout&&reset

    git checkout指令是用来还原一个代码仓库中的文件的。

    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git status
    On branch master
    Changes not staged for commit:
      (use "git add <file>..." to update what will be committed)
      (use "git checkout -- <file>..." to discard changes in working directory)
    
            modified:   test
    
    no changes added to commit (use "git add" and/or "git commit -a")
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git checkout test
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git status
    On branch master
    nothing to commit, working tree clean
    

    在修改文件之后,执行git add指令之前,如果执行checkout指令,则会抛弃当前本地的所有修改,恢复到上次最后的提交版本。

    如果修改文件并执行git add指令后继续修改文件,此时再执行checkout指令,查看代码仓库状态。

    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git status
    On branch master
    Changes not staged for commit:
      (use "git add <file>..." to update what will be committed)
      (use "git checkout -- <file>..." to discard changes in working directory)
    
            modified:   test
    
    no changes added to commit (use "git add" and/or "git commit -a")
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git add test
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git checkout test
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git status
    On branch master
    Changes to be committed:
      (use "git reset HEAD <file>..." to unstage)
    
            modified:   test
    

    git checkout <file>指令其实是用版本库里的版本替换工作区的版本,无论工作区是修改还是删除。

    git reset HEAD <file>指令将一个文件移出暂存区。

    二、回退版本

    在Git中,用HEAD表示当前版本,那么上一个版本就是HEAD^,上上一个版本就是HEAD^^,如果往上100个版本可以写成HEAD~100。

    回退到上个版本

    $ git reset --hard HEAD^
    HEAD is now at 4269b25 添加README
    

    也可以写commit id来表示对应的版本。

    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ touch test2
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git add
    Nothing specified, nothing added.
    Maybe you wanted to say 'git add .'?
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git add test2
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git commit -m "add test2"
    [master c896e52] add test2
     1 file changed, 0 insertions(+), 0 deletions(-)
     create mode 100644 test2
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git lg
    * c896e52 (HEAD -> master)add test2(3 seconds ago)<huangxiaolei>--abbrev-commit
    * 4269b25添加README(76 minutes ago)<huangxiaolei>--abbrev-commit
    
    huangxiaolei@huangxiaolei MINGW64 /f/GitTest (master)
    $ git reset --hard 4269b25
    HEAD is now at 4269b25 添加README
    

    学海无涯苦作舟

    Android成长录.jpg

    相关文章

      网友评论

        本文标题:Git回退

        本文链接:https://www.haomeiwen.com/subject/fjsyzftx.html